1. Concept library
  2. Java & Spring Boot
  3. Module 2: Object-oriented design

Concept

Encapsulation

Keep an object's fields private and expose behaviour through methods, so the object controls its own invariants. Callers get what they need without being able to leave it in a broken state.

What a session covers

The tutor works through these with you, in conversation and code. A session ends when you have shown them, not when a video does.

  1. Explain what an invariant is and how private fields protect it
  2. Write a class that exposes behaviour instead of setters
  3. Spot the generated setter that lets a caller break the invariant

In practice

A few lines that show Encapsulation doing its job.

Java
public class Account {
    private long balanceCents;

    public void withdraw(long cents) {
        if (cents <= 0) throw new IllegalArgumentException("amount must be positive");
        if (cents > balanceCents) throw new InsufficientFundsException(balanceCents, cents);
        balanceCents -= cents;
    }

    public long balanceCents() { return balanceCents; }
}

The common mistake

Watch for

Generating a getter and setter for every field, which is public fields with extra steps. If any code can call setBalance(-500), the class is not guarding anything.

What to know first

Your roadmap puts these before Encapsulation, unless you already know them.

How it stays learned

Once a session shows you understand Encapsulation, it comes back for review. Each review takes a minute and tells the memory model how well you still know it.

  1. Day 3First recall, while it is fresh
  2. Day 7Second, a week on
  3. Day 18Last, when it has settled

Where it leads

Topics that build on Encapsulation.

Next in the moduleComposition →