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.
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.
- 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.
- 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.
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.
// 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.
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.
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(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.
- 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.
- 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.
- • 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.
- 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