Tutorial 1: Classes, Objects, and Encapsulation

Unit 7 ยท Object design

Objectives

A class is a blueprint; an object is an instance. Encapsulation keeps representation private and exposes meaningful operations. A class invariant is a rule that should remain true for every valid object.

public class BankAccount {
    private final String owner;
    private double balance;

    public BankAccount(String owner, double openingBalance) {
        if (openingBalance < 0) throw new IllegalArgumentException("balance");
        this.owner = owner;
        this.balance = openingBalance;
    }
    public void deposit(double amount) {
        if (amount <= 0) throw new IllegalArgumentException("amount");
        balance += amount;
    }
    public double getBalance() { return balance; }
}

Do not expose mutable fields directly. A method can validate an operation and keep the invariant intact.

Practice

  1. Define a StudySession class with topic, minutes, and a validation rule.
  2. Add a method that changes state only when its argument is valid.
  3. List the class's invariant in plain language.

Self-check

  1. Why is this.owner needed in the constructor?
  2. Why should balance be private?
  3. When should a field be final?

Mastery task: Design a CourseProgress class with operations to complete a tutorial, calculate percentage, and reject impossible progress.