Sobes.tech
Junior — Middle

How to ensure immutability of objects in a class?

sobes.tech AI

Answer from AI

To ensure immutability of objects in a Java class, the following practices are usually applied:

  1. Declare the class as final to prevent inheritance and behavior modification.
  2. Make all fields private and final.
  3. Do not provide setters for the fields.
  4. Initialize all fields through the constructor.
  5. If the fields are mutable objects (e.g., arrays or collections), create copies when assigning and returning from getters to prevent external modifications.

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 changing its state.

How to ensure immutability of objects in a class… - sobes.tech