LOW-LEVEL DESIGN · OBJECT-ORIENTED PROGRAMMING · PILLAR · 2 OF 48

Encapsulation in Java: Private State, Invariants and Defensive Copies

How encapsulation keeps an object correct no matter who calls it, shown with a digital wallet: private fields, invariants the object promises to keep, behaviour methods instead of setters, the hidden leak of returning a mutable list, defensive copies in and out, immutable values, and access modifiers, with a runnable Java 17 example.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
1 / 15

Press play to hear the narration, or step through at your own pace. The Java example is below.

Java example

One file, Java 17, 126 lines, with a small main() demo. Save it as EncapsulationDemo.java, then run javac EncapsulationDemo.java && java EncapsulationDemo.

import java.time.Instant;
import java.util.ArrayList;
import java.util.List;

/**
 * Encapsulation with a digital wallet.
 * Part 1: LeakyWallet has public fields, so any caller can break its rules.
 * Part 2: Wallet keeps its data private and protects four invariants:
 *   1) balance is never negative  2) balance equals the sum of all transactions
 *   3) every change has a transaction  4) history is append-only
 */
public class EncapsulationDemo {

    public static void main(String[] args) {
        // ---------- Part 1: the problem ----------
        LeakyWallet leaky = new LeakyWallet();
        leaky.balance = -500;          // nothing stops this
        leaky.history.clear();         // nothing stops this either
        System.out.println("Leaky wallet balance: " + leaky.balance + " (impossible, but allowed)");

        // ---------- Part 2: the clean version ----------
        Wallet wallet = new Wallet(List.of(new Txn(300, "opening bonus", Instant.EPOCH)));
        wallet.addMoney(500, "bank top-up");
        wallet.pay(120, "cafe");
        System.out.println("Balance: " + wallet.balance());

        // Behaviour method refuses a payment that would break invariant 1.
        try {
            wallet.pay(800, "store");
        } catch (IllegalStateException e) {
            System.out.println("Rejected: " + e.getMessage());
        }

        // The getter returns a read-only copy, not the real list.
        List<Txn> seen = wallet.history();
        try {
            seen.clear();
        } catch (UnsupportedOperationException e) {
            System.out.println("Caller cannot clear history: copy is read-only");
        }

        // Copy on the way in: changing the caller's list later does not touch the wallet.
        List<Txn> opening = new ArrayList<>();
        opening.add(new Txn(100, "gift", Instant.EPOCH));
        Wallet second = new Wallet(opening);
        opening.add(new Txn(1_000_000, "fake", Instant.EPOCH));
        System.out.println("Second wallet balance after caller edits its list: " + second.balance());

        System.out.println("History matches balance: " + wallet.isConsistent());
        wallet.history().forEach(t -> System.out.println("  " + t));
    }
}

/** The problem: public, mutable fields. Rules live only in people's heads. */
class LeakyWallet {
    public long balance;
    public List<Txn> history = new ArrayList<>();
}

/** An immutable value: safe to share without copies. */
record Txn(long amount, String party, Instant at) {
    Txn {
        if (amount == 0) {
            throw new IllegalArgumentException("a transaction must move money");
        }
        if (party == null || at == null) {
            throw new IllegalArgumentException("party and time are required");
        }
    }
}

/** The clean version: private state, behaviour methods, defensive copies. */
final class Wallet {
    private long balance;                                // only this class can touch it
    private final List<Txn> history = new ArrayList<>(); // never handed out directly

    /** Copy on the way in, then make the invariants true from the start. */
    Wallet(List<Txn> opening) {
        for (Txn t : new ArrayList<>(opening)) {
            if (balance + t.amount() < 0) {
                throw new IllegalArgumentException("opening transactions go below zero");
            }
            balance += t.amount();
            history.add(t);
        }
    }

    void addMoney(long amount, String from) {
        requirePositive(amount);
        balance += amount;
        history.add(new Txn(amount, from, Instant.now()));
    }

    /** Check, change and record together, so no caller can skip the check. */
    void pay(long amount, String to) {
        requirePositive(amount);
        if (amount > balance) {
            throw new IllegalStateException("cannot pay " + amount + ", only " + balance + " left");
        }
        balance -= amount;
        history.add(new Txn(-amount, to, Instant.now()));
    }

    long balance() {
        return balance;
    }

    /** Copy on the way out: a read-only snapshot. */
    List<Txn> history() {
        return List.copyOf(history);
    }

    boolean isConsistent() {
        long sum = 0;
        for (Txn t : history) {
            sum += t.amount();
        }
        return sum == balance && balance >= 0;
    }

    private static void requirePositive(long amount) {
        if (amount <= 0) {
            throw new IllegalArgumentException("amount must be positive");
        }
    }
}

Notes

The problem

Here is a wallet with public fields. Any code can set the balance to minus five hundred. Any code can add money without writing a transaction, so the history no longer explains the balance. Any code can clear the history list. When a customer complains, you have to search the whole code base to find who touched the field. The rules exist only in people's heads.

A leaky wallet
class LeakyWallet {
  public long balance;
  public List<Txn> history;
}

w.balance = -500;        // allowed
w.balance += 100;        // no record
w.history.clear();       // gone

// bug? search all 300 files

The idea

Encapsulation means keeping an object's data private and allowing changes only through methods that keep its rules true. The wallet becomes the only code that can touch its balance. That has a powerful side effect: if the balance is ever wrong, there is exactly one class to look at. Outside code says what it wants, like pay two hundred, and the wallet decides how.

In one sentence
  • encapsulation: keep an
  • object's data private and
  • allow changes only through
  • methods that keep its rules
  • true
  • the object is the only one
  • that can break itself, so
  • it is the only place to look

Invariants

Before writing the class, list its invariants. An invariant is a promise that holds after every public method finishes. Our wallet promises four things. The balance is never negative. The balance always equals the sum of the transactions. Every change creates a transaction. And history only grows, it is never edited. The constructor makes these true, and every method must keep them true.

Wallet invariants
  • 1 balance is never negative
  • 2 balance equals the sum of
  • all transactions
  • 3 every change has a Txn
  • 4 history is append-only
  • constructor: makes them true
  • every method: keeps them true

Private + behaviour

Now the fields are private. The only way to spend is the pay method. It checks that the amount is positive, checks there is enough balance, subtracts, and records a transaction, all in one place. Because there is no other door into the balance, all four invariants hold no matter how many screens, jobs or services call the wallet.

Wallet.pay()
private long balance;
private final List<Txn> history
    = new ArrayList<>();

void pay(long amount, String to) {
  requirePositive(amount);
  if (amount > balance)
    throw new IllegalStateException(..);
  balance -= amount;
  history.add(new Txn(-amount, to));
}

Setters vs behaviour

A common trap is to make the fields private and then add a getter and a setter for each one. That is a public field with extra typing. The rule now lives in every caller that does read, check, then set. Instead, tell the object what you want. Pay two hundred to the cafe. The check and the change happen together inside the wallet, and nobody can skip the check.

Tell, do not ask
// asking: logic outside the object
if (w.getBalance() >= 200)
  w.setBalance(w.getBalance() - 200);

// telling: logic inside
w.pay(200, "cafe");

a setter for every field is
just a public field with
extra typing

The hidden leak

Private fields are not enough on their own. If get history returns the real internal list, the caller holds a reference to your private data and can clear it or add fake entries. The field was private, but the object behind it escaped. This is the most common encapsulation bug in interviews, and it hides in getters that look completely harmless.

Private, but leaked
List<Txn> getHistory() {
  return history;   // the real list!
}

w.getHistory().clear();
// invariant 2 and 4: broken

Defensive copies

The fix is a defensive copy. On the way out, return List dot copyOf, a read-only snapshot. Trying to add or clear it throws an exception, and it does not change the wallet. On the way in, copy too. If the constructor stored the list the caller passed, the caller could keep changing it afterwards. Copy what you receive, and copy what you give away.

Copy in, copy out
List<Txn> history() {
  return List.copyOf(history);
}

Wallet(List<Txn> opening) {
  history = new ArrayList<>(opening);
  ...
}

copyOf: read-only, throws on add

Immutable values

The cheapest encapsulation is an object that cannot change. A transaction is a record with final fields and no setters, so the list can share transactions freely without copying each one. Java's String, Instant and LocalDate are immutable too. The old java dot util dot Date class is mutable, so a class that stores a Date must copy it, which is one reason the newer time classes replaced it.

record Txn
record Txn(long amount, String party,
           Instant at) { }

final fields, no setters
safe to share and cache
safe across threads

Instant, LocalDate, String: immutable
java.util.Date: mutable, copy it

Run-through

Follow one flow, starting from an empty wallet. The payment screen adds five hundred. The wallet checks the amount, updates the balance and appends a transaction. Then the screen tries to pay eight hundred to a store. The wallet sees only five hundred, refuses, and nothing changes: no half updated balance, no stray transaction. The caller cannot get around this, because there is no other path to the data.

Access modifiers

Java gives you four access levels. Private means this class only. Leaving the word out means package private: any class in the same package. Protected adds subclasses. Public means everyone. Start with private and open up only what callers really need. Every public method is a promise you have to keep, because changing it can break code you do not even know about.

Java access levels
  • private: this class only
  • package-private (no word):
  • same package
  • protected: package +
  • subclasses
  • public: everyone
  • default to private;
  • every public method is a
  • promise you must keep

In the JDK

You use encapsulated classes every day. String has no way to change its characters. List dot of and List dot copyOf give unmodifiable lists. Collections dot unmodifiableList is a read-only view, which is not the same as a copy: if the original list changes, the view shows it. ArrayList keeps its array and size private and changes them only through add and remove. The java dot time classes are all immutable values.

You already use it
  • String: immutable, no setters
  • List.copyOf, List.of:
  • unmodifiable lists
  • Collections.unmodifiableList:
  • read-only view (not a copy)
  • ArrayList: size is private,
  • changes only via add/remove
  • java.time: immutable values

Trade-offs

Some balance. Copying a large list on every call costs memory, so prefer immutable types that need no copies. For plain data that just moves between layers, a record is enough. Do not let your editor generate a getter and setter for every field by habit. The goal is not hiding for its own sake. The goal is that the rules of the object cannot be broken from outside.

Do not overdo it
  • • copies cost memory: prefer
  • immutable types instead
  • • plain data carriers: use a
  • record, skip the ceremony
  • • do not auto-generate a
  • getter and setter per field
  • • hiding is not the goal;
  • protecting rules is

In interviews

In machine coding rounds, encapsulation is how you show correctness. A parking spot changes between free and taken only through park and leave. A bank account refuses an overdraft. In an expense splitter, all balances add up to zero. Name the invariant out loud and show which method protects it. Typical mistakes are public fields, getters that return internal lists, and setters that skip the checks.

Where it shows up
  • parking spot: free or taken,
  • changed only by park/leave
  • bank account: no overdraft
  • splitwise: balances sum to 0
  • inventory: stock never < 0
  • mistakes: public fields,
  • returning internal lists,
  • setters that skip checks

Interview questions

What is encapsulation?

Encapsulation is bundling data with the methods that operate on it and restricting direct access to that data. Outside code changes the object only through its public methods, which enforce the object's rules, so the object can never be put into an invalid state from outside.

Is a class with private fields and public getters and setters encapsulated?

Only in name. If every field has a plain setter, callers can still put the object into any state, and the rules end up duplicated in the callers. Real encapsulation exposes meaningful operations, such as pay or withdraw, that check and change state together.

What is a class invariant?

A condition that is true for every valid object of the class, such as a balance that is never negative. The constructor establishes it and every public method preserves it, so callers can always rely on it between method calls.

What is a defensive copy and when do you need one?

A defensive copy is a copy of mutable data made when it enters or leaves an object, so that outside code cannot change the object's internal state through a shared reference. You need it for mutable inputs and outputs such as lists, arrays and java.util.Date, but not for immutable types.

What is the difference between Collections.unmodifiableList and List.copyOf?

Collections.unmodifiableList returns a read-only view over the original list, so changes made to the original still show through. List.copyOf returns an unmodifiable copy that is independent of the source. Both throw UnsupportedOperationException on modification attempts.

How does immutability relate to encapsulation?

An immutable object has final state and no methods that change it, so it cannot be broken after construction and can be shared without copies, even across threads. It is the strongest form of encapsulation and removes the need for defensive copies.

What are the access modifiers in Java?

private (only the declaring class), package-private with no keyword (classes in the same package), protected (the same package plus subclasses) and public (everyone). A good default is the most restrictive level that still works.

Why does encapsulation make code easier to change?

Callers depend only on the public methods, not on how the data is stored. You can change the internal representation, for example from a list to a map, without touching any caller, as long as the public behaviour stays the same.