Java Β· Module 6 Β· Lesson 21 min read

Encapsulation & Inheritance

Encapsulation: protect your data πŸ”

Keep fields private and expose safe methods. This lets you validate changes.

Java
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

ModifierSame classSame packageSubclassEverywhere
privateβœ…βŒβŒβŒ
(none)βœ…βœ…βŒβŒ
protectedβœ…βœ…βœ…βŒ
publicβœ…βœ…βœ…βœ…

Inheritance: reuse with extends 🧬

A subclass gets the fields and methods of its superclass and can add or change behaviour.

Java
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 where toString(), equals() and hashCode() come from.
  • A final class can't be extended, and a final method can't be overridden.

IS-A vs HAS-A

  • Inheritance = IS-A: a SavingsAccount is an Account.
  • Composition = HAS-A: a Car has an Engine, so give it an Engine field instead. πŸ’‘ Prefer composition when "is-a" doesn't sound right.

Example

Java
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
    }
}