Do you know Java: Immutable Object


Couple of thoughts about how to implement immutable objects.

  1. Class has to be final.
  2. Fields have to be private and final.
  3. Hence, fields are set in constructor.
  4. No setters and setter-like methods.
  5. 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 if PhoneNumber 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