Junior — Middle
How to ensure immutability of objects in a class?
sobes.tech AI
Answer from AI
To ensure immutability of objects in a Java class, the following practices are usually applied:
- Declare the class as
finalto prevent inheritance and behavior modification. - Make all fields
privateandfinal. - Do not provide setters for the fields.
- Initialize all fields through the constructor.
- If the fields are mutable objects (e.g., arrays or collections), create copies when assigning and returning from getters to prevent 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, after object creation, does not allow changing its state.