Do you know Java: Immutable Object
Couple of thoughts about how to implement immutable objects.
- Class has to be
final
. - Fields have to be
private
andfinal
. - Hence, fields are set in constructor.
- No setters and setter-like methods.
- If object is passed in ctor parameter, make a clone of it.
- Do the same in getters as well.
public final class Person {
private final String name;
private final int age;
private final List<PhoneNumber> phoneNumbers;
public Person(String name, int age, List<PhoneNumber> phoneNumbers) {
this.name = name;
this.age = age;
this.phoneNumbers = new ArrayList<>(phoneNumbers);
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public List<PhoneNumber> getPhoneNumbers() {
return new ArrayList<>(phoneNumbers);
}
}
It is also very important to mention that
PhoneNumber
should be immutable as well. But what ifPhoneNumber
is not immutable?Person
class still has to be.Why do not we clone the objects? Cloning is not a recommended way in Java, try to avoid it.
Implementation steps of immutable object is a recurring question on technical interviews.
Code can be found: https://github.com/torokmark/do-you-know-java