Junior — Middle
How to implement a class whose instances cannot be modified after creation in Java?
sobes.tech AI
Answer from AI
To make a class in Java immutable, you should:
- Declare the class as
finalso it cannot be subclassed and its behavior cannot be changed. - 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 of them when passing to the constructor and when returning from getters.
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;
}
}