Inheritance

Inheritance defines an is-a relationship. EmailNotification extends Notification means an email notification can be used anywhere a Notification is expected.

A subclass inherits accessible members from its superclass and can add specialized state or behavior. super(...) initializes the parent portion of the object.

Extend an existing type

class Account {
    String owner;

    Account(String owner) {
        this.owner = owner;
    }

    void showStatus() {
        System.out.println(owner + ": active");
    }
}

class SavingsAccount extends Account {
    SavingsAccount(String owner) {
        super(owner);
    }

    void addInterest() {
        System.out.println("Interest added");
    }
}

public class Main {
    public static void main(String[] args) {
        SavingsAccount account =
                new SavingsAccount("Maya");
        account.showStatus();
        account.addInterest();
    }
}

Output:

Maya: active
Interest added

SavingsAccount inherits showStatus from Account and adds its own addInterest behavior. Because Account has no constructor without parameters, the SavingsAccount constructor must call super(owner) to pass the name up to Account.

Java classes have one direct superclass. Deep inheritance trees become rigid, so use them only for stable conceptual relationships.

Make Dog extend Animal and pass its name to the parent constructor.