Junior — Middle
What principles should be used when creating a class in Java to make it immutable?
sobes.tech AI
Answer from AI
To make a class in Java immutable, you need to follow several principles:
- Declare the class as
final— so that it cannot be subclassed to alter behavior. - Make all fields
privateandfinal— so they cannot be changed after initialization. - Do not provide setters (methods to modify fields).
- Initialize all fields through the constructor.
- If fields are references to mutable objects (e.g., arrays, collections), create copies when assigning and returning from getters, so external changes do not affect 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 a class, after object creation, does not allow changing its state, which is useful for thread safety and predictable behavior.