Skip to the workspace
Pebellslearn by building
Object-Oriented Principles  ›  Lesson

Inheritance

Inheritance 14 minA subclass extends one superclass, inheriting its fields and methods, and its constructor must first build the parent part with super.

java / Inheritance

Explore each scene at your own pace.

01 · The rule

The rule

Inheritance

A subclass extends one superclass, inheriting its fields and methods, and its constructor must first build the parent part with super.

Follow inherited behavior and initialization through a superclass and subclass.

Brew Bar starts selling iced drinks. An iced latte is still a drink, with a name and a price, but it also needs an amount of ice. Copying the whole Drink class into a new file would mean fixing every future bug twice. Inheritance lets IcedDrink reuse everything Drink already has and add only what is new.

The rule

extends means "is a": the child gets everything and adds more.

public class Drink {
    protected String name;
    protected int priceCents;

    public Drink(String name, int priceCents) {
        this.name = name;
        this.priceCents = priceCents;
    }

    public String label() {
        return name + " (" + priceCents + "c)";
    }
}

public class IcedDrink extends Drink {
    private int iceGrams;

    public IcedDrink(String name, int priceCents, int iceGrams) {
        super(name, priceCents);   // build the Drink part first
        this.iceGrams = iceGrams;
    }
}

Drink is the superclass (parent) and IcedDrink the subclass (child). The child automatically has name, priceCents and label(), and adds iceGrams. Private members of the parent still exist inside the child object but cannot be named from the child's code, which is why these fields are protected.

Rules that follow:

  • super(...) builds the parent part. It must be the first statement of the child's constructor. If you leave it out, Java inserts super() with no arguments, which fails to compile here, because Drink has no such constructor.
  • Parents are built first. Constructors run from the top of the family tree down.
  • One parent only. A class can extend exactly one class. (Several interfaces are allowed, as you will see.)
  • Everything extends Object in the end, which is where methods like toString() and equals() come from.
  • A child can stand in for its parent. Drink d = new IcedDrink("Iced latte", 330, 80); is fine, because an iced drink is a drink. The reverse is not.
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.