Loading published curriculum…

02 · Objects and collections / LESSON 4 OF 102

Classes and encapsulation

Objects should protect their invariants.

Before this lesson: Methods, arrays, and debugging

Understand the topic

Constructors establish valid state. private fields prevent callers from bypassing rules; instance fields belong to each object, while static members belong to the class. final prevents reassignment, not deep mutation of referenced objects.

Prefer composition when one object uses another. Inheritance should model a substitutable relationship. Keep behavior near the state it controls.

EXAMPLE · JAVA

Main.java

class Task {
    private final String title;
    private boolean done;
    Task(String title) {
        if (title == null || title.isBlank())
            throw new IllegalArgumentException("Title required");
        this.title = title;
    }
    void complete() { done = true; }
    String summary() { return title + ": " + done; }
}
public class Main {
    public static void main(String[] args) {
        Task task = new Task("Learn Java");
        task.complete();
        System.out.println(task.summary());
    }
}

What to expect

Learn Java: true

YOUR TURN

Put it into practice

  1. 01Add a reopen method.
  2. 02Try a blank title.
  3. 03Explain why title is private and final.

Pass a quiz or complete a lab to check today’s streak. Each lesson counts once per day, including when you review it later.

UNDER THE HOOD

Build the mental model

An object owns rules as well as data. Encapsulation is useful when it prevents invalid states, not merely when it adds getters and setters.

  1. 01A constructor should either return a valid object or fail. A public setter that bypasses the constructor rule destroys that guarantee.
  2. 02Separate identity from display text: two tasks can have the same title but be different tasks. Do not base persistent identity on a mutable title.
  3. 03Prefer small behavior methods such as complete() over exposing a mutable status field that callers can set arbitrarily.

A mistake worth avoiding

A final List reference does not prevent list.add; final prevents assigning a different list.

DEBUGGING ROOM

Something broke. Where do you look?

A task is created with a valid title but later becomes blank.

Before revealing the diagnosis, write down your first investigation step.

CHECK YOUR UNDERSTANDING

What does final on a field containing an ArrayList prevent?

Choose one answer

BUILD IT YOURSELF

Model a task lifecycle

  1. 1.Add TODO, IN_PROGRESS, and DONE states.
  2. 2.Provide start, complete, and reopen operations.
  3. 3.Reject invalid transitions with a meaningful exception.

Acceptance checklist

Lab completion is your self-report. Knowledge checks do not certify project quality.

RETRIEVE IT FROM MEMORY

Which invariants does your constructor establish?

Revisit this lesson in three days after a successful check or lab.

Ready for the next step?

Construct valid objects and control state changes.

Reading is separate from passing a knowledge check or completing a lab.

Go deeper · official references