Object-oriented basics · Chapter 2

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.

IntermediateInterview priority: Medium45 min
On this page
  1. The problem: anyone can break the rules
  2. The idea: the object guards its own data
  3. How it works: a complete account
  4. Getters and setters are not encapsulation
  5. Immutability: the strongest encapsulation
  6. Options and trade-offs
  7. When not to bother
  8. In the interview
  9. Quiz

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

  1. 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

  1. Encapsulation means hiding the fields and offering a few safe methods instead. The balance becomes private: only code inside Account can touch it.
  2. 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

  1. 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]
    }
}

Three things make this encapsulated, not just "private fields":

  1. Every path that changes state checks the invariant first. The constructor validates the opening balance; withdraw refuses before it subtracts.
  2. Nothing internal leaks. history() returns a copy. Returning the real list would let any caller append fake transactions, and private would mean nothing.
  3. 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.

DesignWhat callers can doInvariant safe?
public long balanceAnythingNo
private balance + getBalance() + setBalance()Anything, through a methodNo
private balance + deposit() + withdraw() + getBalance()Only meaningful, checked operationsYes

Read through a getter, change only through checked operations

  1. 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);
    }
}

The 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

ApproachGood atWeak atUse when
Mutable class, private state, checked methodsThings that genuinely change: accounts, carts, elevatorsNeeds locks when shared between threadsThe object has a life story
Immutable value (record, frozen dataclass)Thread safety, map keys, caching, reasoningAllocates a new object per changeMoney, dates, coordinates, configuration, messages
Plain data with public fieldsShort, honest DTOs with no rulesAny invariantData 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

Your turn: a shopping cart

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);
    }
}

A 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.

Your turn: spot the leak

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
}

A 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.

Encapsulation on one page
  • 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: _name is a convention, __name mangles, @property gives read-only access, frozen=True dataclasses.
  • Information hiding: callers never see the representation, so you can change it in one class.
Interactive labPractise it: guard the vaultOpens in the ByteAtlas lab. Your progress is saved in this browser.
Check what stuck

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?

2. A class stores private final List<Order> orders and has public List<Order> getOrders() { return orders; }. What is the risk?

3. Why are immutable objects safe to share between threads without locks?

4. In Python, a class stores the balance in self.__balance. What does the double underscore actually do?

5. A Meeting is a frozen dataclass with attendees: list. A colleague says it is immutable. What do you say?

6. Which change to Account is easiest because the balance was encapsulated from the start?

Score 60% or more and the lesson is marked complete.

Passing the quiz also marks it complete. Progress is saved in this browser only.