Inheritance and Polymorphism in Java

Inheritance lets a class reuse and extend another class, and polymorphism lets code written for the parent type work with any subclass, calling each object's own version of a method. Together they are the core of object-oriented Java, and also the source of some of its most subtle bugs. This page shows how method calls are dispatched, the order in which objects are built, the rules for overriding, and why composition is often the safer choice.

Contents

Inheritance and polymorphism in a nutshell

When class Manager extends Employee, a Manager is an Employee: it inherits the parent's fields and methods, can add its own, and can override methods to change their behavior. Every class extends exactly one class (Object if none is named), so Java has single inheritance of classes; a class can implement many interfaces.

Polymorphism means that a variable of the parent type can hold any subclass object, and calling an overridden method runs the version of the object's actual class. This is dynamic dispatch: the method is chosen when the program runs, not when it compiles.

What a subclass inherits
MemberInherited?Notes
Public and protected fields and methodsYesUsable directly in the subclass
Package-private membersOnly if in the same package
Private fields and methodsPresent in the object, but not accessibleReach them through the parent's methods
ConstructorsNoEach class declares its own and calls super(...)
Static methodsAccessible, but hidden rather than overriddenChosen by the declared type

Dynamic dispatch and super

The program builds a payroll with one ordinary employee and one manager whose pay adds a bonus. The list is declared as List<Employee>, so the loop does not know which kind of employee it is processing. The figures were chosen so the total is easy to check: 4,000 + 5,000 + 1,500 = 10,500.

Java
import java.util.List;

public class Dispatch {

    static class Employee {
        protected final String name;
        protected final double baseSalary;

        Employee(String name, double baseSalary) {
            this.name = name;
            this.baseSalary = baseSalary;
            System.out.println("  Employee constructor for " + name);
        }

        double pay() {
            return baseSalary;
        }

        String title() {
            return "Employee";
        }

        @Override
        public String toString() {
            return String.format("%-9s %-6s %8.2f", title(), name, pay());
        }
    }

    static class Manager extends Employee {
        private final double bonus;

        Manager(String name, double baseSalary, double bonus) {
            super(name, baseSalary);                 // must be the first statement
            this.bonus = bonus;
            System.out.println("  Manager constructor for " + name);
        }

        @Override
        double pay() {
            return super.pay() + bonus;              // reuse the parent's logic
        }

        @Override
        String title() {
            return "Manager";
        }
    }

    public static void main(String[] args) {
        System.out.println("constructing:");
        List<Employee> staff = List.of(
                new Employee("Ann", 4000),
                new Manager("Bo", 5000, 1500));

        System.out.println("payroll:");
        double total = 0;
        for (Employee e : staff) {                   // declared type Employee...
            System.out.println("  " + e);            // ...but each object's own methods run
            total += e.pay();
        }
        System.out.printf("total %.2f%n", total);
    }
}

Output:

Output
constructing:
  Employee constructor for Ann
  Employee constructor for Bo
  Manager constructor for Bo
payroll:
  Employee  Ann     4000.00
  Manager   Bo      6500.00
total 10500.00
  • Creating Bo ran the Employee constructor first, then the Manager one: super(name, baseSalary) must be the first statement, so the parent part of an object is always built before the child part.
  • The loop variable is an Employee, yet Bo's line says "Manager" and 6,500.00: title() and pay() ran the Manager versions. Even toString, written once in Employee, called the overridden methods.
  • super.pay() calls the parent's version from inside the override, so the manager's pay reuses the base salary logic and adds to it.
  • This is what polymorphism buys: the payroll loop never changes when new kinds of employees are added.

Overloading versus overriding

Overloading (same name, different parameter types) and overriding (same signature in a subclass) look similar but are resolved at different times. The program calls both through a variable declared as Animal but holding a Dog.

Java
public class OverloadVsOverride {

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

        static String kind() {
            return "animal";
        }
    }

    static class Dog extends Animal {
        @Override
        String sound() {                       // overriding: chosen at run time
            return "woof";
        }

        static String kind() {                 // hiding: chosen at compile time
            return "dog";
        }
    }

    // Overloads: chosen at compile time from the DECLARED argument type
    static String greet(Animal a) {
        return "greet(Animal)";
    }

    static String greet(Dog d) {
        return "greet(Dog)";
    }

    public static void main(String[] args) {
        Animal pet = new Dog();

        System.out.println("pet.sound():  " + pet.sound());   // Dog's version
        System.out.println("greet(pet):   " + greet(pet));    // Animal overload
        System.out.println("greet((Dog) pet): " + greet((Dog) pet));
        System.out.println("Animal.kind(): " + Animal.kind() + ", Dog.kind(): " + Dog.kind());

        // Fields are not polymorphic either
        Base b = new Derived();
        System.out.println("field via Base reference:    " + b.label);
        System.out.println("field via Derived reference: " + ((Derived) b).label);
    }

    static class Base {
        String label = "base";
    }

    static class Derived extends Base {
        String label = "derived";              // a second, separate field that hides Base.label
    }
}

Output:

Output
pet.sound():  woof
greet(pet):   greet(Animal)
greet((Dog) pet): greet(Dog)
Animal.kind(): animal, Dog.kind(): dog
field via Base reference:    base
field via Derived reference: derived
  • pet.sound() printed "woof": overriding is resolved at run time from the object's class.
  • greet(pet) chose greet(Animal), even though the object is a Dog: overloading is resolved at compile time from the declared type of the argument. Casting to Dog selected the other overload.
  • Static methods and fields are not polymorphic. Dog.kind() hides Animal.kind(), and a field with the same name in a subclass is a second, separate field. Which one you get depends on the declared type, as the two field reads show. Avoid hiding: it is legal but misleading.
Overloading compared with overriding
OverloadingOverriding
WhereSame class (or a subclass)A subclass
SignatureDifferent parameter typesSame name and parameter types
ChosenAt compile time, by declared argument typesAt run time, by the object's class
Return typeAnythingSame, or a subtype (covariant)

The order in which objects are built

Static and instance initialization of a parent and child class runs in a fixed order that matters whenever one part depends on another. The program logs every step: static fields and blocks, instance fields, an instance initializer block and constructors, for two objects in a row.

Java
public class InitOrder {

    static String log(String message) {
        System.out.println("  " + message);
        return message;
    }

    static class Parent {
        static String s = log("1. Parent static field");
        String f = log("Parent instance field");

        static {
            log("2. Parent static block");
        }

        Parent() {
            log("Parent constructor body");
        }
    }

    static class Child extends Parent {
        static String s = log("3. Child static field");
        String f = log("Child instance field");

        static {
            log("4. Child static block");
        }

        {
            log("Child instance initializer block");
        }

        Child() {
            super();                       // runs the whole Parent part first
            log("Child constructor body");
        }
    }

    public static void main(String[] args) {
        System.out.println("first new Child():");
        new Child();
        System.out.println("second new Child(): static parts do not run again");
        new Child();
    }
}

Output:

Output
first new Child():
  1. Parent static field
  2. Parent static block
  3. Child static field
  4. Child static block
  Parent instance field
  Parent constructor body
  Child instance field
  Child instance initializer block
  Child constructor body
second new Child(): static parts do not run again
  Parent instance field
  Parent constructor body
  Child instance field
  Child instance initializer block
  Child constructor body
  • Static parts run once, when each class is first used, parent before child, and in source order within each class (field, then block). The second new Child() did not run them again.
  • For each object, the whole parent part (its instance fields, then its constructor body) is complete before the child's instance fields are even initialized.
  • Within a class, instance field initializers and initializer blocks run in source order, before the constructor body.
  • This order is why calling an overridable method from a parent constructor is dangerous: the child's fields are not yet set. The abstract classes page shows that trap with real output.

Override rules and traps

An override must match the parent's method exactly, or it silently becomes something else. The program writes equals(Point) instead of equals(Object), a mistake found in real code bases, and then uses a covariant return type, which is legal and useful.

Java
import java.util.HashSet;
import java.util.Set;

public class OverrideTraps {

    // Trap 1: equals(Point) OVERLOADS equals(Object) instead of overriding it
    static final class Point {
        final int x;
        final int y;

        Point(int x, int y) {
            this.x = x;
            this.y = y;
        }

        public boolean equals(Point other) {          // no @Override, so no error
            return other != null && x == other.x && y == other.y;
        }

        @Override
        public int hashCode() {
            return 31 * x + y;
        }
    }

    // Covariant return type: an override may return a subtype
    static class Shape {
        Shape copy() {
            return new Shape();
        }
    }

    static class Circle extends Shape {
        final double r;

        Circle(double r) {
            this.r = r;
        }

        @Override
        Circle copy() {                               // returns Circle, not Shape
            return new Circle(r);
        }
    }

    public static void main(String[] args) {
        Point a = new Point(1, 2);
        Point b = new Point(1, 2);
        Object asObject = b;
        System.out.println("a.equals(b) with Point type:  " + a.equals(b));
        System.out.println("a.equals(b) with Object type: " + a.equals(asObject));
        Set<Point> set = new HashSet<>();
        set.add(a);
        System.out.println("HashSet contains equal point: " + set.contains(b));

        Circle c = new Circle(2.5);
        Circle copy = c.copy();                       // no cast needed
        System.out.println("covariant copy radius: " + copy.r);
    }
}

Output:

Output
a.equals(b) with Point type:  true
a.equals(b) with Object type: false
HashSet contains equal point: false
covariant copy radius: 2.5
  • equals(Point) does not override equals(Object); it is an overload. Called with a Point argument it worked, but called through an Object reference, Java chose the inherited Object.equals, which compares identity, and returned false. HashSet calls equals(Object), so it could not find an equal point.
  • Writing @Override on the method would have made this a compile error: "method does not override or implement a method from a supertype". Put @Override on every override; it costs nothing and catches typos and wrong parameter types.
  • Circle.copy() returns Circle while Shape.copy() returns Shape. An override may narrow the return type (covariant return, Java 5), so callers holding a Circle need no cast.
Rules for a valid override
RuleDetail
Same name and parameter typesOtherwise it is an overload
Return typeSame, or a subtype for reference types
AccessSame or wider; never narrower (see access modifiers)
Checked exceptionsSame, narrower or none; never new or broader ones
Not allowed forfinal, static and private methods

When inheritance goes wrong

Two classic problems show the limits of inheritance. The first extends HashSet to count how many elements were added; the second makes a Square a subclass of Rectangle. Both compile and look reasonable.

Java
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class FragileBaseClass {

    // Inheritance: counts every element ever added... or tries to
    static class CountingSet<E> extends HashSet<E> {
        int added;

        @Override
        public boolean add(E e) {
            added++;
            return super.add(e);
        }

        @Override
        public boolean addAll(Collection<? extends E> c) {
            added += c.size();
            return super.addAll(c);              // HashSet.addAll calls add() for each element
        }
    }

    // Composition: wraps a set instead of extending it
    static class CountingSetWrapper<E> {
        private final Set<E> inner = new HashSet<>();
        int added;

        boolean add(E e) {
            added++;
            return inner.add(e);
        }

        boolean addAll(Collection<? extends E> c) {
            added += c.size();
            return inner.addAll(c);              // inner calls its own add, not ours
        }
    }

    // Liskov substitution: a Square "is a" Rectangle mathematically, but not in code
    static class Rectangle {
        int width;
        int height;

        void setWidth(int w) {
            width = w;
        }

        void setHeight(int h) {
            height = h;
        }

        int area() {
            return width * height;
        }
    }

    static class Square extends Rectangle {
        @Override
        void setWidth(int w) {
            width = w;
            height = w;
        }

        @Override
        void setHeight(int h) {
            width = h;
            height = h;
        }
    }

    static int stretch(Rectangle r) {           // written for rectangles
        r.setWidth(5);
        r.setHeight(4);
        return r.area();                        // a caller expects 20
    }

    public static void main(String[] args) {
        CountingSet<String> inherited = new CountingSet<>();
        inherited.addAll(List.of("a", "b", "c"));
        System.out.println("extends HashSet: added 3 elements, counter says " + inherited.added);

        CountingSetWrapper<String> wrapped = new CountingSetWrapper<>();
        wrapped.addAll(List.of("a", "b", "c"));
        System.out.println("wraps a HashSet: added 3 elements, counter says " + wrapped.added);

        System.out.println("stretch(new Rectangle()) = " + stretch(new Rectangle()));
        System.out.println("stretch(new Square())    = " + stretch(new Square()));
    }
}

Output:

Output
extends HashSet: added 3 elements, counter says 6
wraps a HashSet: added 3 elements, counter says 3
stretch(new Rectangle()) = 20
stretch(new Square())    = 16
  • The counting subclass reported 6 additions for 3 elements. Its addAll added 3, then called HashSet.addAll, which internally calls add for each element, and that add is the overridden one, which counted again. The subclass depended on an implementation detail of its parent that is not part of the documented contract and could change in any release. This is the fragile base class problem.
  • The wrapper version holds a HashSet instead of being one, so the inner set's internal calls never reach the wrapper's methods, and it counted correctly. Preferring this composition over inheritance is the standard advice for classes you do not control.
  • stretch sets a width of 5 and a height of 4 and expects an area of 20. For a Square it got 16, because setting the height also changed the width. A subclass must work everywhere its parent works (the Liskov substitution principle); a mutable square cannot keep the promises of a mutable rectangle, even though mathematically every square is a rectangle.

Inheritance, interfaces or composition?

Choosing how to reuse code
SituationUse
A genuine "is a" relationship within code you control, with shared stateInheritance, often from an abstract class
Several unrelated types that share a capabilityAn interface, with default methods if useful
Adding behavior to a class you do not ownComposition: wrap it and delegate
Different behavior per type, chosen at run timeOverriding, or a strategy object or lambda passed in
A fixed set of subtypes handled in one placeA sealed hierarchy with pattern matching
Classes not designed for extensionMake them final

Joshua Bloch's advice in Effective Java sums it up: design and document for inheritance, or else prohibit it.