Sobes.tech
Junior — Middle

How can a class be implemented so that its state is immutable after creation?

sobes.tech AI

Answer from AI

To create an immutable class in Java, you should:

  • Make the class final so it cannot be subclassed and its behavior cannot be changed.
  • Declare all fields as private final.
  • Initialize all fields through the constructor.
  • Do not provide setters (methods to modify fields).
  • If fields are mutable objects (e.g., arrays, collections), create copies of them when passing to the constructor and when returning from getters.

Example:

public final class ImmutablePerson {
    private final String name;
    private final int age;

    public ImmutablePerson(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

Such a class, after object creation, does not allow its state to be changed.