Sobes.tech
Senior

How to make a class immutable?

sobes.tech AI

Answer from AI

In Java, a class is made immutable so that its state cannot be changed after creation. To do this:

  1. Declare the class as final so it cannot be subclassed and its behavior altered.
  2. Make all fields private and final.
  3. Do not provide setters (methods to modify fields).
  4. Initialize all fields through the constructor.
  5. If fields are mutable objects (e.g., arrays, collections), create copies of them when passing to the constructor and when returning from getters, so external changes do not affect the internal state.

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 does not allow its fields to be changed after the object is created.

How to make a class immutable? — Java - sobes.tech