Junior — Middle
What methods can be used to implement immutability of classes in programming?
sobes.tech AI
Answer from AI
To implement immutable classes in Java, the following methods are usually used:
- Declare the class as
finalto prevent inheritance and behavior modification. - Make all fields
privateandfinalso they cannot be changed after initialization. - Do not provide setters (methods to modify fields).
- Initialize all fields through the constructor.
- If fields contain references to mutable objects, create copies of them when passing to the constructor and when returning from getters (protection against 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.