Inheritance and super

OOP · lesson 5 of 43 · 3 min read

How extends shares state and behaviour, how super works, and when inheritance is the wrong tool.

Open this lesson in the learning hub

Key points

  • extends means IS-A. A subclass gets every field and method of its parent and can add its own.
  • Java allows one parent class only. Interfaces are how a type takes on many roles at once.
  • The parent constructor always runs first. super(...) must be the first statement, or Java inserts super().
  • @Override is optional but always worth writing. It turns a silent typo into a compile error.
  • Mark a class or method final when subclassing it would break the assumptions you rely on.
  • Inheritance couples you to the parent forever. Use it for a genuine IS-A, never just to reuse a handy method.

Example

public class Main {
    static class Vehicle {
        protected final String id;

        Vehicle(String id) { this.id = id; }

        String describe() { return "Vehicle " + id; }

        void start() { System.out.println(describe() + " -> starting"); }
    }

    static class ElectricCar extends Vehicle {
        private final int kwh;

        ElectricCar(String id, int kwh) {
            super(id);                 // parent constructor runs first, always
            this.kwh = kwh;
        }

        @Override String describe() {
            return super.describe() + " (electric, " + kwh + " kWh)";
        }
    }

    public static void main(String[] args) {
        new Vehicle("V-1").start();

        ElectricCar e = new ElectricCar("E-9", 77);
        e.start();                     // start() is inherited, describe() is overridden
        System.out.println("is a Vehicle? " + (e instanceof Vehicle));
    }
}

Inherit only when the subclass truly IS the parent, everywhere the parent is used.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the OOP course, and every lesson in it is listed on the OOP contents page.