How to create an Immutable object in Java?

How to create an Immutable object in Java?

In Java, an immutable object is an object whose state cannot be modified after it has been created. This means that once an immutable is instantiated, its state remains constant throughout its lifetime. Immutable are useful for ensuring thread safety, simplifying code, and preventing unintended modifications to object state.

 Immutable object

1. Immutable Object Properties

  • Immutable have properties that cannot be changed after instantiation.
  • They typically have final fields, meaning that their values are set only once during object creation and cannot be modified thereafter.
  • Immutable should have no setters or methods that modify their internal state.

2. Thread Safety

  • Immutable are inherently thread-safe because their state cannot be changed once they are created.
  • Multiple threads can safely access and share immutable without the risk of concurrent modification issues.

3. Example of Immutable Objects

   Common examples of immutable in Java include String, Integer, BigDecimal, and LocalDate.

Example
java
public final class ImmutableObject {
    private final int value;
    private final String name;

    // Constructor initializes the final fields
    public ImmutableObject(int value, String name) {
        this.value = value;
        this.name = name;
    }

    // Getter methods to access the fields (no setters)
    public int getValue() {
        return value;
    }

    public String getName() {
        return name;
    }
}

In this example, ImmutableObject is a class representing an immutable with two final fields: value and name. These fields are set only once via the constructor, and there are no setter methods provided. The class is marked as final to prevent subclassing, which could potentially modify the behavior of the object. This ensures that instances of ImmutableObject cannot be modified once created, making them immutable.

Homepage

Readmore