Senior
How to create an Immutable (unchangeable) class in Java?
sobes.tech AI
Answer from AI
To create an immutable class in Java, you need to:
- Make the class final so it cannot be subclassed or have its behavior changed.
- Make all fields private and final.
- Do not provide setters.
- Initialize all fields through the constructor.
- If fields are mutable objects, return their copies in getters to prevent modification of 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;
}
}
If there are fields of collection types or other objects, you should return their copies or use immutable collections.