Encapsulation & Inheritance
Encapsulation: protect your data π
Keep fields private and expose safe methods. This lets you validate changes.
public class Account {
private double balance;
public double getBalance() { return balance; }
public void deposit(double amount) {
if (amount <= 0) throw new IllegalArgumentException("Amount must be positive");
balance += amount;
}
}
Nobody can set balance = -1000 directly any more. π
Access modifiers
| Modifier | Same class | Same package | Subclass | Everywhere |
|---|---|---|---|---|
private | β | β | β | β |
| (none) | β | β | β | β |
protected | β | β | β | β |
public | β | β | β | β |
Inheritance: reuse with extends π§¬
A subclass gets the fields and methods of its superclass and can add or change behaviour.
public class SavingsAccount extends Account {
private final double rate;
public SavingsAccount(double rate) {
super(); // call the parent constructor (must be first)
this.rate = rate;
}
public void addInterest() {
deposit(getBalance() * rate);
}
}
super(...)calls the parent constructor;super.method()calls the parent's version of a method.- A class can extend only one class.
- Every class secretly extends
Object, which is wheretoString(),equals()andhashCode()come from. - A
finalclass can't be extended, and afinalmethod can't be overridden.
IS-A vs HAS-A
- Inheritance = IS-A: a
SavingsAccountis anAccount. - Composition = HAS-A: a
Carhas anEngine, so give it anEnginefield instead. π‘ Prefer composition when "is-a" doesn't sound right.
Example
class Account {
private double balance;
public double getBalance() { return balance; }
public void deposit(double amount) {
if (amount <= 0) throw new IllegalArgumentException("Must be positive");
balance += amount;
}
}
class SavingsAccount extends Account {
private final double rate;
SavingsAccount(double rate) { this.rate = rate; }
void addInterest() { deposit(getBalance() * rate); }
}
public class Bank {
public static void main(String[] args) {
SavingsAccount acc = new SavingsAccount(0.05);
acc.deposit(1000);
acc.addInterest();
System.out.println(acc.getBalance()); // 1050.0
}
}