Inheritance and super

A Bike is a Vehicle. Reuse the parent's fields and methods, and call its constructor with super(...).

Java · beginner · 8 min · 13 steps · free

What you'll learn

InheritanceDemo.java

class Vehicle {
    int wheels;

    Vehicle(int wheels) {
        this.wheels = wheels;
    }

    String describe() {
        return "a vehicle with " + wheels + " wheels";
    }
}

class Bike extends Vehicle {
    boolean hasBell;

    Bike() {
        super(2);
        hasBell = true;
    }
}

public class InheritanceDemo {
    public static void main(String[] args) {
        Bike bike = new Bike();
        String text = bike.describe();
        System.out.println(text + ", bell: " + bike.hasBell);
    }
}

Step by step

  1. new Bike(): Java starts building a Bike, which is also a Vehicle.
  2. super(2) runs Vehicle's constructor first, setting wheels to 2.
  3. Java enters the constructor. Before its own code runs, the parent class's constructor (here Object) runs first.
  4. wheels in the Bike object changes from 0 to 2.
  5. Vehicle() has finished, so its variables are gone.
  6. Now the Bike's own field.
  7. Bike() has finished, so its variables are gone.
  8. new Bike(): Java starts building a Bike, which is also a Vehicle.
  9. describe() is not in Bike, so Java uses the one inherited from Vehicle.
  10. describe() has finished, so its variables are gone.
  11. The value it returned, "a vehicle with 2 wheels", is stored in text.
  12. It prints a vehicle with 2 wheels, bell: true.
  13. One Bike object holds both wheels (from Vehicle) and hasBell (its own).

Common mistakes

Best practices

Key takeaways

Check yourself

Can a Java class extend two classes?

Answer: No: only one. Java allows single class inheritance (but many interfaces).

Which constructor runs first for new Bike()?

Answer: Vehicle's. The parent part is built first.

·

More in Object-Oriented Programming