Unit 7 ยท Object design
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.
StudySession class with topic, minutes, and a validation rule.this.owner needed in the constructor?final?Mastery task: Design a CourseProgress class with operations to complete a tutorial, calculate percentage, and reject impossible progress.