Course outline · 0% complete

0/29 lessons0%

Course overview →

extends and super

lesson 6-1 · ~10 min · 16/29

Quiz

Warm-up from lesson 5-3: why did we mark Player's score field private?

Inheritance

Classes often form families: a Dog is an Animal, a SavingsAccount is a BankAccount. Without a language feature for this, the shared parts get copy-pasted into every family member, and a bug fix must be repeated in each copy — the exact disease methods cured within one class, now at the scale of whole classes. Inheritance lets a class reuse another class's fields and methods with extends. It is also how you plug into other people's code: professional Java means extending framework classes (an Android screen extends Activity) far more often than writing hierarchies from scratch:

class Animal {
  String name;

  Animal(String name) {
    this.name = name;
  }

  void eat() {
    System.out.println(name + " is eating");
  }
}

class Dog extends Animal {
  Dog(String name) {
    super(name);  // run Animal's constructor first
  }

  void fetch() {
    System.out.println(name + " fetches the ball");
  }
}

Dog is the subclass, Animal the superclass. A Dog object has everything Animal declared (name, eat) plus its own additions (fetch). super(...) calls the superclass constructor and must be the first line when the parent needs arguments. Python's class Dog(Animal) and super().__init__(name) are the same idea.

Code exercise · java

Run this. The Dog object can use eat() even though Dog never defined it, because it inherits from Animal.

What gets inherited

A subclass inherits every field and method except constructors and anything private (private members exist in the object but are only reachable through the parent's own methods). Each class can extend exactly one superclass. Chains are fine: Puppy extends Dog extends Animal.

When should you use inheritance? Only for a true is-a relationship. A Dog is an Animal, so Dog extends Animal reads naturally. A Car has an Engine, so Engine should be a field inside Car, not a superclass. "Is-a gets extends, has-a gets a field" prevents most inheritance misuse you will ever be tempted by.

Code exercise · java

Your turn. Create Vehicle with an int field wheels, a constructor, and describe() printing `has <wheels> wheels`. Then Motorcycle extends Vehicle: its no-argument constructor calls super(2), and wheelie() prints `up on one wheel!`. Main builds a Motorcycle and calls both methods.