Sobes.tech
Junior

What ensures immutability in Java?

sobes.tech AI

Answer from AI

Immutability in Java is ensured by the following methods:

  1. Declaring a class as final: The class cannot be inherited, which prevents the creation of mutable subclasses.

  2. Declaring all fields as final: The value of a field can only be assigned once (during initialization or in the constructor) and cannot be changed after the object is created.

  3. Private fields: Fields should be private (private) to prevent direct access and modification of values from outside the class.

  4. Absence of setters or methods that modify the object's state: The class should not provide public methods that can change the value of the object's fields after its creation.

  5. Proper handling of mutable fields: If the class contains references to mutable objects (e.g., List or a custom mutable class), it is necessary to:

    • Create copies of them during initialization (in the constructor).
    • Return copies in getters to avoid external modification of the internal state of the object.
public final class ImmutableExample { // final class

    private final String name; // final and private field

    private final List<String> items; // final and private field

    public ImmutableExample(String name, List<String> items) {
        this.name = name;
        // Creating a protected copy of the mutable list
        this.items = new ArrayList<>(items);
    }

    public String getName() {
        return name;
    }

    public List<String> getItems() {
        // Returning a protected copy of the mutable list
        return Collections.unmodifiableList(new ArrayList<>(items));
    }

    // No setters or methods that change the state
}

Examples of built-in immutable classes in Java: String, primitive wrapper classes (Integer, Long, etc.), BigInteger, BigDecimal.