Middle
What needs to be done to make the Person class immutable?
sobes.tech AI
Answer from AI
To make the Person class immutable in Java, you need to:
- Make the class
finalso it cannot be subclassed or have its behavior changed. - Declare all class fields as
private final. - Initialize all fields through the constructor.
- Do not provide setters.
- If the fields are mutable objects (e.g., collections or other classes), create copies when assigning and return copies in getters to prevent external modification of internal state.
Example:
public final class Person {
private final String name;
private final int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}