Sobes.tech
Junior — Middle

How can you create a class whose objects cannot be modified after initialization?

sobes.tech AI

Answer from AI

To create an immutable class in Java, you need to:

  • Make the class final so it cannot be subclassed and its behavior cannot be changed.
  • Declare all fields as private final.
  • Initialize all fields through the constructor.
  • Do not provide setters (methods to modify fields).
  • If fields are mutable objects, create copies of them when passing and returning (protection from 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 cannot be modified after object creation.

How can you create a class whose objects cannot be… - sobes.tech