Junior — Middle
Is it sufficient to declare a class as final, hide fields with private, and avoid setters to achieve immutability of an object after its initialization?
sobes.tech AI
Answer from AI
Declaring a class as final, hiding fields as private, and avoiding setters are important steps in creating an immutable object, but they are not sufficient for complete immutability.
For an object to be truly immutable after initialization, you need to:
- Make all fields final (if using Java) so they cannot be changed after assignment.
- If fields are references to mutable objects (e.g., collections), create copies of them during initialization and return copies or immutable views to prevent external modifications from affecting the internal state.
- The absence of setters prevents modification of fields from outside.
- The final class prevents inheritance, which excludes the possibility of changing behavior through subclasses.
Example:
public final class ImmutablePerson {
private final String name;
private final List<String> hobbies;
public ImmutablePerson(String name, List<String> hobbies) {
this.name = name;
this.hobbies = new ArrayList<>(hobbies); // copy of the list
}
public String getName() {
return name;
}
public List<String> getHobbies() {
return Collections.unmodifiableList(hobbies); // return an unmodifiable list
}
}
Thus, merely declaring the class as final and making fields private without additional measures does not guarantee complete immutability.