Junior — Middle
How can an object of a class be made immutable after its creation?
sobes.tech AI
Answer from AI
To make a class object in Java immutable, you need to:
- Declare the class as final so it cannot be subclassed and its behavior cannot be changed.
- Make all fields private and final so they cannot be modified after initialization.
- Do not provide setters for the fields.
- Initialize all fields through the constructor.
- If the fields are mutable objects (e.g., collections), create copies of them when assigning and returning through getters to prevent 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 an object cannot be changed after creation.