CSE Roadmap

Core tier · about 2 hours · 7 parts

Part 6 of 7 · 2 min read

Immutable classes

The strongest form of encapsulation.

Immutable classes

EJ Item 17 says to minimise mutability. An immutable class is one whose instances cannot be modified. All its data is fixed for the lifetime of the object. Java's String and the boxed number classes are examples. EJ says such classes are simpler to build and to use than mutable ones, cause fewer errors, and are safer.

The five rules from EJ, in my own words: 1. No methods that change the object's state. 2. The class cannot be extended, usually by making it final, so that a subclass cannot sneak in changes. 3. All fields are final, which states the intent and is also needed for safe sharing between threads. 4. All fields are private. 5. Any mutable part must be kept exclusive: never store a caller's mutable object directly, and never return your own. Make defensive copies.

An immutable class makes "change" mean "make a new object". EJ's complex number class returns a new Complex from plus. A made-up Money with the same idea:

final class Cash {
    private final long cents;
    Cash(long cents) { this.cents = cents; }
    long cents() { return cents; }
    Cash plus(Cash other) { return new Cash(cents + other.cents); }
}

new Cash(500).plus(new Cash(250)).cents() is 750, and neither input changes. Such objects can be shared freely, between threads too, because no one can alter them.

Immutability does cost one thing: a new object for each change. Records in modern Java make the shape short, but a record holding a mutable List still breaks rule 5, so copy the list in the constructor.

Common mistake

Making fields final and then returning the internal List from a getter. The caller can still change the list, so the object is not really immutable.

Interview angle

Answer in your head first, then open it.

What is encapsulation?

Hiding data and details behind a small API, so the class can keep its rules and change inside.

Why prefer private fields with methods?

The class can enforce invariants and change its representation without breaking callers.

How do you make a class immutable?

No mutators, final class, final private fields, and defensive copies of mutable parts.

Check yourself: 1. Which two of the five rules stop subclasses and callers from changing state? 2. What does plus return in an immutable class? 3. Why is returning an internal list a problem?

Words you will meet

Word Meaning
Encapsulation Hiding data and details behind a small API
Information hiding Another name for encapsulation
Access modifier private, protected or public, or none for package-private
Getter, setter Methods that read or change a field
Invariant A rule about the data that must always hold
Immutable Cannot change after it is built
Defensive copy A private copy of a mutable object, made at the boundary