Encapsulation
Hide fields behind methods so an object can protect its own rules. Invariants, why getters and setters are not enough, defensive copies and immutable objects, in Java and Python.
On this page
The problem: anyone can break the rules
A bank's Account class starts with a public field:
class Account {
public long balanceCents;
}
account.balanceCents -= 90_000; // a withdrawal, written in some controller
The rule "the balance is never negative" is written nowhere. Every piece of code that withdraws money has to remember to check it, and one that forgets (a refund job, a script someone wrote at 2 a.m.) leaves the account at minus 600 dollars. When that happens, there are fifty places that could have done it.
A public field: anyone can write anything
- Here is a bank account object with a balance of 300 dollars. If the balance field is public, any code anywhere can reach in and write anything, even a negative balance.
The idea: the object guards its own data
Encapsulation means keeping an object's data private and letting the outside world change it only through methods the object controls. The fields become private; the class offers a few operations (deposit, withdraw) that check the rules before touching anything.
Private fields, public methods that check the rules
- Encapsulation means hiding the fields and offering a few safe methods instead. The balance becomes private: only code inside Account can touch it.
- Now the account protects its own rules. A direct write won’t even compile, and withdraw(900) from a 300 balance is refused. A rule that must always be true, like “balance is never negative”, is called an invariant.
A rule that must hold for every object, at every moment that outside code can see it, is called an invariant. "Balance is never negative", "a meeting ends after it starts", "a cart's total equals the sum of its lines" are invariants. Encapsulation is what lets you write each invariant down once, inside the class, instead of hoping every caller remembers it.
The payoff is not only safety. Because nobody outside knows how the balance is stored, you can change that freely: this is information hiding.
Change the insides without breaking any caller
- There’s a second reward, information hiding. Because nobody outside knows how the balance is stored, you can change the insides, say to whole cents to avoid rounding errors, by editing one class. Every caller keeps working.
How it works: a complete account
The account below enforces its invariants in the constructor and in every method that changes state. It stores money as whole cents in a long (never a double: binary floating point cannot represent 0.10 exactly, and the errors add up). The transaction history is kept private and handed out as a read-only view.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
public class Account {
private final String id; // never changes
private long balanceCents; // invariant: >= 0
private final List<String> history = new ArrayList<>();
public Account(String id, long openingCents) {
if (openingCents < 0) throw new IllegalArgumentException("opening balance cannot be negative");
this.id = Objects.requireNonNull(id);
this.balanceCents = openingCents;
history.add("open " + openingCents);
}
public synchronized void deposit(long cents) {
if (cents <= 0) throw new IllegalArgumentException("deposit must be positive");
balanceCents += cents;
history.add("deposit " + cents);
}
public synchronized void withdraw(long cents) {
if (cents <= 0) throw new IllegalArgumentException("withdrawal must be positive");
if (cents > balanceCents) throw new IllegalStateException("insufficient funds");
balanceCents -= cents; // only reached when the rule holds
history.add("withdraw " + cents);
}
public synchronized long balanceCents() { return balanceCents; }
public String id() { return id; }
public synchronized List<String> history() {
return Collections.unmodifiableList(new ArrayList<>(history)); // a copy callers cannot change
}
public static void main(String[] args) {
Account acc = new Account("ACC-1", 30_000);
acc.withdraw(10_000);
try {
acc.withdraw(90_000);
} catch (IllegalStateException e) {
System.out.println("refused: " + e.getMessage()); // refused: insufficient funds
}
System.out.println(acc.balanceCents()); // 20000
try {
acc.history().add("withdraw 1000000");
} catch (UnsupportedOperationException e) {
System.out.println("history is read-only");
}
System.out.println(acc.history()); // [open 30000, withdraw 10000]
}
}import threading
class InsufficientFunds(Exception):
pass
class Account:
def __init__(self, account_id: str, opening_cents: int):
if opening_cents < 0:
raise ValueError("opening balance cannot be negative")
self._id = account_id # leading underscore: "internal, don't touch"
self._balance_cents = opening_cents # invariant: >= 0
self._history = [f"open {opening_cents}"]
self._lock = threading.Lock()
@property
def id(self) -> str:
return self._id
@property
def balance_cents(self) -> int: # read-only: there is no setter
return self._balance_cents
def deposit(self, cents: int) -> None:
if cents <= 0:
raise ValueError("deposit must be positive")
with self._lock:
self._balance_cents += cents
self._history.append(f"deposit {cents}")
def withdraw(self, cents: int) -> None:
if cents <= 0:
raise ValueError("withdrawal must be positive")
with self._lock:
if cents > self._balance_cents:
raise InsufficientFunds("insufficient funds")
self._balance_cents -= cents
self._history.append(f"withdraw {cents}")
def history(self) -> tuple:
with self._lock:
return tuple(self._history) # an immutable copy
if __name__ == "__main__":
acc = Account("ACC-1", 30_000)
acc.withdraw(10_000)
try:
acc.withdraw(90_000)
except InsufficientFunds as e:
print("refused:", e) # refused: insufficient funds
print(acc.balance_cents) # 20000
try:
acc.balance_cents = 10**9
except AttributeError:
print("balance has no setter")
print(acc.history()) # ('open 30000', 'withdraw 10000')Three things make this encapsulated, not just "private fields":
- Every path that changes state checks the invariant first. The constructor validates the opening balance;
withdrawrefuses before it subtracts. - Nothing internal leaks.
history()returns a copy. Returning the real list would let any caller append fake transactions, andprivatewould mean nothing. - Check and change happen together.
synchronized(or the lock in Python) makes "is there enough money?" and "subtract it" one step. See the box below for why.
Getters and setters are not encapsulation
A class with a private field and a public setBalance(long) is a public field with extra steps. Encapsulation is about which operations exist, not about wrapping every field.
| Design | What callers can do | Invariant safe? |
|---|---|---|
public long balance | Anything | No |
private balance + getBalance() + setBalance() | Anything, through a method | No |
private balance + deposit() + withdraw() + getBalance() | Only meaningful, checked operations | Yes |
Read through a getter, change only through checked operations
- Other code can still read the balance through a getter, getBalance(), but it can’t change it behind the account’s back. A good default: make fields private, and only make a method public when someone really needs it.
The rule of thumb is tell, don't ask: instead of asking an object for its data and deciding outside (if (acc.getBalance() >= x) acc.setBalance(acc.getBalance() - x)), tell it what you want (acc.withdraw(x)) and let it decide. The asking version also has a race built in.
Immutability: the strongest encapsulation
An immutable object cannot change after it is built. Validate in the constructor once, and the invariant holds forever, with no locks: immutable objects are safe to share between threads, safe to use as map keys and safe to cache. "Changing" one means making a new object.
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
public record Meeting(String title, LocalDateTime start, LocalDateTime end, List<String> attendees) {
public Meeting { // compact constructor: runs before fields are set
Objects.requireNonNull(title);
if (!end.isAfter(start)) throw new IllegalArgumentException("meeting must end after it starts");
attendees = List.copyOf(attendees); // defensive copy, and immutable
}
public Meeting withEnd(LocalDateTime newEnd) { // "change" = new object
return new Meeting(title, start, newEnd, attendees);
}
}from dataclasses import dataclass, replace
from datetime import datetime
@dataclass(frozen=True)
class Meeting:
title: str
start: datetime
end: datetime
attendees: tuple # a tuple, not a list, so it cannot be changed in place
def __post_init__(self):
if self.end <= self.start:
raise ValueError("meeting must end after it starts")
object.__setattr__(self, "attendees", tuple(self.attendees)) # copy whatever was passed
def with_end(self, new_end: datetime) -> "Meeting":
return replace(self, end=new_end) # runs __post_init__ again, so the rule still holdsThe recipe for an immutable class: all fields final (or a record / frozen dataclass), no setters, validate in the constructor, defensively copy mutable inputs, and never hand out a mutable internal. In Java also make the class final (records already are), so a subclass cannot add mutable state.
Options and trade-offs
| Approach | Good at | Weak at | Use when |
|---|---|---|---|
| Mutable class, private state, checked methods | Things that genuinely change: accounts, carts, elevators | Needs locks when shared between threads | The object has a life story |
| Immutable value (record, frozen dataclass) | Thread safety, map keys, caching, reasoning | Allocates a new object per change | Money, dates, coordinates, configuration, messages |
| Plain data with public fields | Short, honest DTOs with no rules | Any invariant | Data crossing a boundary (JSON, rows) with no behaviour |
When not to bother
- Data transfer objects that only carry fields between layers have no invariants to protect. A record or a dataclass with public fields is honest about that.
- Private helper classes used in one file don't need a getter for every field.
- Don't encapsulate for its own sake. If every getter is paired with a setter "just in case", you have the ceremony with none of the benefit; ask which operations the object really needs to offer.
In the interview
A cart holds lines (product id, unit price in cents, quantity). Rules: quantity is 1 to 10 per line, and the cart total must always match the lines. Design the public methods and say how each rule is protected. Give code in Java and Python.
Compare with our answer
import java.util.LinkedHashMap;
import java.util.Map;
public class Cart {
private record Line(long unitCents, int qty) { }
private final Map<String, Line> lines = new LinkedHashMap<>();
public void add(String productId, long unitCents, int qty) {
if (unitCents <= 0) throw new IllegalArgumentException("price must be positive");
Line old = lines.get(productId);
int newQty = (old == null ? 0 : old.qty()) + qty;
if (qty < 1 || newQty > 10) throw new IllegalArgumentException("quantity must be 1 to 10");
lines.put(productId, new Line(unitCents, newQty));
}
public void remove(String productId) { lines.remove(productId); }
public long totalCents() { // computed, so it can never drift
long t = 0;
for (Line l : lines.values()) t += l.unitCents() * l.qty();
return t;
}
public Map<String, Integer> quantities() {
Map<String, Integer> out = new LinkedHashMap<>();
lines.forEach((id, l) -> out.put(id, l.qty()));
return Map.copyOf(out);
}
}class Cart:
def __init__(self):
self._lines = {} # product_id -> (unit_cents, qty)
def add(self, product_id: str, unit_cents: int, qty: int) -> None:
if unit_cents <= 0:
raise ValueError("price must be positive")
old_qty = self._lines.get(product_id, (0, 0))[1]
if qty < 1 or old_qty + qty > 10:
raise ValueError("quantity must be 1 to 10")
self._lines[product_id] = (unit_cents, old_qty + qty)
def remove(self, product_id: str) -> None:
self._lines.pop(product_id, None)
@property
def total_cents(self) -> int: # computed, so it can never drift
return sum(price * qty for price, qty in self._lines.values())
def quantities(self) -> dict:
return {pid: qty for pid, (_, qty) in self._lines.items()} # a new dictA strong answer mentions: lines kept private · add and remove as the only ways to change the cart · the quantity rule checked before any change · the total computed from the lines rather than stored separately (so it cannot drift) · a copy returned to callers · money in integer cents.
This class claims to be immutable. Find two ways a caller can still change a Team after it is built.
public final class Team {
private final String name;
private final List<String> members;
public Team(String name, List<String> members) { this.name = name; this.members = members; }
public List<String> members() { return members; }
}Compare with our answer
(1) The constructor stores the caller's list, so the caller can keep a reference and add to it later. (2) members() returns the same list, so anyone can call team.members().clear(). Fix both ends with a defensive copy into an immutable list.
public final class Team {
private final String name;
private final List<String> members;
public Team(String name, List<String> members) {
this.name = Objects.requireNonNull(name);
this.members = List.copyOf(members); // copy in; List.copyOf is immutable
}
public List<String> members() { return members; } // safe to share now
}from dataclasses import dataclass
@dataclass(frozen=True)
class Team:
name: str
members: tuple
def __post_init__(self):
object.__setattr__(self, "members", tuple(self.members)) # copy in, immutableA strong answer mentions: final on a field does not freeze the object it points to · copying on the way in · not returning the mutable internal · List.copyOf (or a tuple in Python) so the copy itself is immutable · that once the list is immutable, returning it directly is safe.
- Private fields, public operations. Callers say what they want (
withdraw), the object decides. - Invariant = a rule that always holds for the object; enforce it in the constructor and every mutating method.
- Getters + setters for every field ≠ encapsulation. Expose behaviour, not data. Tell, don't ask.
- Don't leak internals: copy mutable inputs in, return copies or immutable views out.
- Check-then-act must be atomic:
synchronized/lock, or a conditional update in the database. - Immutable objects: final fields, no setters, validate once, copy deeply; thread-safe and safe as keys.
- Python:
_nameis a convention,__namemangles,@propertygives read-only access,frozen=Truedataclasses. - Information hiding: callers never see the representation, so you can change it in one class.
1. A Seat class has a private bookedBy field with a public setBookedBy(String user). Two users end up holding the same seat. What is the best fix?
The rule "one holder per seat" belongs inside Seat, in an operation that checks and writes as one step. A getter-then-setter in the caller is check-then-act and still races.
2. A class stores private final List<Order> orders and has public List<Order> getOrders() { return orders; }. What is the risk?
final freezes the reference, not the list. Return List.copyOf(orders) or an unmodifiable view so the class keeps control of its contents.
3. Why are immutable objects safe to share between threads without locks?
Races need a write. With no writes after construction (and final fields published safely), every thread sees the same complete state.
4. In Python, a class stores the balance in self.__balance. What does the double underscore actually do?
Name mangling prevents accidental collisions with subclass attributes. It is not access control: obj._Account__balance still works.
5. A Meeting is a frozen dataclass with attendees: list. A colleague says it is immutable. What do you say?
frozen=True blocks attribute assignment only. Mutable contents stay mutable, so convert to a tuple (and copy) in __post_init__.
6. Which change to Account is easiest because the balance was encapsulated from the start?
Because callers only use deposit, withdraw and the getter, the internal representation can change in one class. The other options weaken the encapsulation rather than benefit from it.
Score 60% or more and the lesson is marked complete.