Sobes.tech
Junior — Middle

What principles should be used when creating a class in Java to make it immutable?

sobes.tech AI

Answer from AI

To make a class in Java immutable, you need to follow several principles:

  1. Declare the class as final — so that it cannot be subclassed to alter behavior.
  2. Make all fields private and final — so they cannot be changed after initialization.
  3. Do not provide setters (methods to modify fields).
  4. Initialize all fields through the constructor.
  5. If fields are references to mutable objects (e.g., arrays, collections), create copies when assigning and returning from getters, so external changes do not affect 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, after object creation, does not allow changing its state, which is useful for thread safety and predictable behavior.

What principles should be used when creating a class… - sobes.tech