Java Tutorial · Object-Oriented Java · Lesson 21 of 37

Java Inheritance and Polymorphism

Extend classes, override methods, call super and use polymorphism.

extends

A subclass inherits fields and methods from its superclass and can override methods. super calls the parent's constructor or methods. @Override asks the compiler to check you really are overriding something.

Example 1
public class Main {
    public static void main(String[] args) {
        Employee e = new Employee("Ada", 5000);
        Manager m = new Manager("Lin", 7000, 1500);
        System.out.println(e.describe());
        System.out.println(m.describe());
    }
}

class Employee {
    protected final String name;
    protected final double salary;

    Employee(String name, double salary) {
        this.name = name;
        this.salary = salary;
    }

    double monthlyPay() {
        return salary;
    }

    String describe() {
        return name + " earns " + monthlyPay();
    }
}

class Manager extends Employee {
    private final double bonus;

    Manager(String name, double salary, double bonus) {
        super(name, salary);
        this.bonus = bonus;
    }

    @Override
    double monthlyPay() {
        return super.monthlyPay() + bonus;
    }
}

Output

Ada earns 5000.0
Lin earns 8500.0

Run this on your computer — see “Get Started” for setup.

Polymorphism

A variable of the parent type can hold any subclass object. When you call an overridden method, Java runs the version for the actual object type — that's polymorphism:

Example 2
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Animal> zoo = List.of(new Dog(), new Cat(), new Animal());
        for (Animal a : zoo) {
            System.out.println(a.getClass().getSimpleName() + ": " + a.sound());
        }
    }
}

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

class Dog extends Animal {
    @Override
    String sound() { return "Woof"; }
}

class Cat extends Animal {
    @Override
    String sound() { return "Meow"; }
}

Output

Dog: Woof
Cat: Meow
Animal: ...

Run this on your computer — see “Get Started” for setup.

Java supports single inheritance for classes (one parent), but a class can implement many interfaces.

Test yourself

How many classes can a Java class directly extend?

  1. One
  2. Two
  3. Unlimited
  4. None
Show answer

Answer: One