← All lessons
Intermediate Java · Lesson 3 of 9

Inheritance

Some classes are special kinds of others: a savings account is a kind of bank account, a dog is a kind of animal. Inheritance lets a class take everything another class has and add to it or change parts. The new class is the subclass; the one it builds on is the superclass. You write it with extends.

Java
public class Main {
    static class Animal {
        protected String name;

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

        String sound() { return "..."; }

        String describe() { return name + " says " + sound(); }
    }

    static class Dog extends Animal {
        Dog(String name) { super(name); }

        @Override
        String sound() { return "Woof"; }

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

    static class Cat extends Animal {
        Cat(String name) { super(name); }

        @Override
        String sound() { return "Meow"; }
    }

    public static void main(String[] args) {
        Dog d = new Dog("Rex");
        System.out.println(d.describe());
        d.fetch();
        System.out.println(new Cat("Tom").describe());
        System.out.println(new Animal("Blob").describe());
    }
}
Prints
Rex says Woof
Rex fetches the ball
Tom says Meow
Blob says ...

A Dog has everything an Animal has (the name field and describe method) without writing them again. It overrides sound with its own version and adds fetch, which only dogs have. super(name) in the constructor runs the superclass's constructor first, so the animal part gets set up. protected lets subclasses use name while keeping it hidden from other code.

Notice that describe is written once, in Animal, but calls the right sound for each object. Java picks the method by what the object really is when the program runs, not by the type of the variable.

Polymorphism

Because a Dog is an Animal, a variable or array of type Animal can hold dogs and cats alike. Call a method on each and every object answers in its own way. This is called polymorphism ("many shapes") and it's one of the main reasons to use inheritance: code written for Animal works for any kind of animal, even ones added later.

Java
public class Main {
    static class Shape {
        double area() { return 0; }
    }

    static class Circle extends Shape {
        private final double r;
        Circle(double r) { this.r = r; }
        @Override double area() { return Math.PI * r * r; }
    }

    static class Square extends Shape {
        private final double side;
        Square(double side) { this.side = side; }
        @Override double area() { return side * side; }
    }

    public static void main(String[] args) {
        Shape[] shapes = { new Circle(1), new Square(3), new Square(0.5) };
        double total = 0;
        for (Shape s : shapes) {
            total += s.area();
        }
        System.out.printf("%.2f%n", total);
    }
}
Prints
12.39

The loop doesn't know or care which shape it has. Through a Shape variable you can only call methods Shape declares, though: fetch() on an Animal variable won't compile, even if it holds a dog. To use dog-only methods, check and convert with instanceof: if (a instanceof Dog dog) dog.fetch();.

Using super

An overriding method can still call the superclass's version with super.method(), to add to it rather than replace it:

Java
public class Main {
    static class Employee {
        protected final String name;
        protected final int salary;
        Employee(String name, int salary) { this.name = name; this.salary = salary; }
        int pay() { return salary; }
    }

    static class Manager extends Employee {
        private final int bonus;
        Manager(String name, int salary, int bonus) {
            super(name, salary);
            this.bonus = bonus;
        }
        @Override int pay() { return super.pay() + bonus; }
    }

    public static void main(String[] args) {
        Employee[] staff = { new Employee("Ana", 3000), new Manager("Ben", 4000, 500) };
        for (Employee e : staff) System.out.println(e.name + " " + e.pay());
    }
}
Prints
Ana 3000
Ben 4500

Object, the top of the tree

Every class extends something. If you don't say what, it extends Object, so every object in Java has Object's methods, like toString() and equals(). That's why overriding toString changes how any object prints. A class can extend only one superclass; the next lesson shows interfaces, which lift that limit.

Use inheritance for a real "is a kind of" relationship. If it's "has a" (a car has an engine), give the class a field instead. Deep chains of subclasses get hard to follow quickly.

Practice

What does this print?

public class Main {
    static class Vehicle {
        int wheels() { return 4; }
    }
    static class Bike extends Vehicle {
        @Override int wheels() { return 2; }
    }

    public static void main(String[] args) {
        Vehicle v = new Bike();
        System.out.println(v.wheels());
    }
}
More info

Quick reference

class B extends AB gets everything A has; B is a kind of A.
super(...)Run the superclass's constructor (first line).
super.method()Call the superclass's version.
@OverrideReplace an inherited method; the compiler checks the name.
protectedVisible to subclasses (and the package).
polymorphismOne variable type, many object types; each runs its own method.
x instanceof Dog dIs x a Dog? If so, d is it as a Dog.
ObjectThe class every class extends in the end.

Related courses