Sobes.tech
Junior — Middle

How can an object be made immutable after its creation?

sobes.tech AI

Answer from AI

To make an object immutable in Java, you should:

  • Declare the class as final so it cannot be subclassed and its behavior cannot be changed.
  • Make all fields private and final so they cannot be modified after initialization.
  • Do not provide setters (methods to modify fields).
  • Initialize all fields through the constructor.
  • If fields are mutable objects (e.g., collections), create copies of them when passing to the constructor and when returning from getters, so external changes do not affect the object's 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;
    }
}
How can an object be made immutable after its… - sobes.tech