Immutable Classes and Defensive Copies

Make an object that can never change: final fields, copies in and out, and "with" methods that return new objects.

Java · intermediate · 8 min · 24 steps · free

What you'll learn

ImmutableDemo.java

import java.util.ArrayList;
import java.util.List;

final class Team {                                   // final: no subclass can change behaviour
    private final String name;
    private final List<String> members;

    Team(String name, List<String> members) {
        this.name = name;
        this.members = new ArrayList<>(members);       // defensive copy in
    }

    List<String> members() {
        return List.copyOf(members);                   // read-only copy out
    }

    Team withMember(String m) {                        // "changes" make a new object
        List<String> more = new ArrayList<>(members);
        more.add(m);
        return new Team(name, more);
    }
}

public class ImmutableDemo {
    public static void main(String[] args) {
        List<String> start = new ArrayList<>(List.of("ana"));
        Team t1 = new Team("blue", start);
        start.add("hacker");                            // does not affect t1
        Team t2 = t1.withMember("ben");
        System.out.println(t1.members() + " " + t2.members());
    }
}

Step by step

  1. The program starts in main. args holds its command-line arguments (none here). start is created on the stack and points to a new ArrayList on the heap: ["ana"].
  2. Create a team from a list we still hold.
  3. Java enters the constructor. Before its own code runs, the parent class's constructor (here Object) runs first.
  4. name in the Team object changes from null to "blue".
  5. A defensive copy: the team keeps its own list, not ours.
  6. Team() has finished, so its variables are gone.
  7. Create a team from a list we still hold.
  8. We change our original list…
  9. Java calls withMember(), with m = "ben". It gets its own variables on the stack.
  10. withMember never changes this team; it builds a new one with the extra member.
  11. "ben" is added to the end of the ArrayList that more points to.
  12. Java runs the Team constructor to set up the new object, with name = "blue" and members = ["ana", "ben"].
  13. Java enters the constructor. Before its own code runs, the parent class's constructor (here Object) runs first.
  14. name in the Team object changes from null to "blue".
  15. members in the Team object changes from null to an ArrayList.
  16. Team() has finished, so its variables are gone.
  17. withMember() has finished, so its variables are gone.
  18. The value it returned, {name: "blue", members: an ArrayList}, is stored in t2.
  19. Java calls members(). It gets its own variables on the stack.
  20. members() has finished, so its variables are gone.
  21. Java calls members(). It gets its own variables on the stack.
  22. members() has finished, so its variables are gone.
  23. It prints [ana] [ana, ben].
  24. t1 is still [ana]; t2 is [ana, ben]. Nothing outside the class could change either.

Common mistakes

Best practices

Key takeaways

Check yourself

Why copy the list in the constructor?

Answer: So the caller cannot change it afterwards. Defensive copying.

String is immutable. What does s.toUpperCase() do?

Answer: Returns a new string. Like withMember.

·

More in More Language Features