Video in progress

What steps does writing an immutable class need, and which one is most often forgotten?

Make the class final, make all fields private final, don't add setters, set all the values in the constructor, and make copies of mutable objects (List, Date) both when they come in and when they go out. "Modifying" methods should return a new object.

📖 Answer

public final class Address {
    private final String city;
    private final String street;
    private final List<String> phones;

    public Address(String city, String street, List<String> phones) {
        this.city = Objects.requireNonNull(city);
        this.street = Objects.requireNonNull(street);
        this.phones = List.copyOf(phones);      // even if the outside list changes, we're unaffected
    }

    public String city() { return city; }
    public List<String> phones() { return phones; }   // List.copyOf is already immutable

    public Address withCity(String newCity) {
        return new Address(newCity, street, phones);
    }
}

Why final class? Otherwise someone could write a child class and make the methods mutable.

The benefit: you can share it between threads without synchronization, it is a reliable HashMap key (the hash never changes), and the state is validated once in the constructor and is correct from then on.

On Java 16+, a record is enough in many cases, since it makes the fields private final automatically. But don't forget to do List.copyOf in the compact constructor for a List inside a record, too.