Sobes.tech
Junior — Middle

How can you ensure the immutability of an object in code?

sobes.tech AI

Answer from AI

To ensure immutability of an object in Java:

  • Make the class 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).
  • If fields are mutable objects (e.g., arrays or 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 an object cannot be changed after creation.

How can you ensure the immutability of an object in… - sobes.tech