Sobes.tech
Junior — Middle

What ways can ensure that an object cannot be modified after initialization?

sobes.tech AI

Answer from AI

To make an object in Java immutable after initialization, you can use the following approaches:

  • Declare the class as final so it cannot be subclassed and behavior cannot be overridden.
  • Make all fields private final so they cannot be changed after assignment.
  • Initialize all fields through the constructor.
  • Do not provide setters (methods to modify fields).
  • If fields are mutable objects (e.g., collections), return their copies or use immutable wrappers (e.g., Collections.unmodifiableList).

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;
    }
}

If there are collections:

private final List<String> items;

public ImmutableClass(List<String> items) {
    this.items = Collections.unmodifiableList(new ArrayList<>(items));
}

public List<String> getItems() {
    return items;
}

Thus, the object cannot be changed after creation.

What ways can ensure that an object cannot be… - sobes.tech