Junior — Middle
How to implement a class whose properties cannot be changed after creating an object?
sobes.tech AI
Answer from AI
To create a class in Java whose objects cannot be modified after creation (immutable), you need to:
- Declare the class as
final(to prevent inheritance and behavior modification). - Make all fields
privateandfinal. - Do not provide setters (methods to modify fields).
- Initialize all fields through the constructor.
- If fields are references to mutable objects, create copies of them when assigning and returning (to avoid 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;
}
}
This class guarantees that once an object is created, its state will not change.