Lesson 2 of 12 · 10 min · Object-oriented Java

Inheritance and polymorphism

Covers: Java 25 LTS (also valid on 21). Updated 13 Nov 2026. Part of the Java Full Stack Developer roadmap.

What you will learn

  • extends, super and constructor chaining
  • Overriding versus overloading
  • How polymorphism picks the method at run time (dynamic dispatch)
  • Upcasting, downcasting and pattern matching with instanceof
  • final, sealed and when to prefer composition over inheritance

In simple words

Inheritance lets a new class start from an existing one and add or change a few things, like a "Car" that is a kind of "Vehicle". Polymorphism means "many shapes": you can hold any kind of vehicle in a variable called Vehicle and ask it to start(), and each kind starts itself in its own way. The caller does not need to know which kind it is.

Words to know

  • Inheritance: a subclass reusing the fields and methods of a superclass.
  • Override: a subclass replacing a method it inherited with its own version.
  • Polymorphism: the same call behaving differently depending on the actual object.
  • Upcast: treating a subclass object as its superclass type.

extends and super

public class Employee {
    private final String name;
    protected double baseSalary;

    public Employee(String name, double baseSalary) {
        this.name = name;
        this.baseSalary = baseSalary;
    }
    public String name() { return name; }
    public double salary() { return baseSalary; }
    @Override public String toString() { return name + " earns " + salary(); }
}

public class Manager extends Employee {
    private final double bonus;

    public Manager(String name, double baseSalary, double bonus) {
        super(name, baseSalary);          // must be the first statement: calls the superclass constructor
        this.bonus = bonus;
    }

    @Override
    public double salary() {              // overrides Employee.salary()
        return super.salary() + bonus;    // reuse the parent's version
    }
}
  • Manager is-a Employee: it inherits name() and everything else.
  • A constructor must call a superclass constructor (super(...)); if you do not, Java inserts super() and fails if there is no no-argument constructor.
  • Java has single inheritance of classes: a class has one superclass (but can implement many interfaces).
  • Everything ultimately extends Object.
  • protected lets subclasses (and the same package) see a member; prefer private with accessors.

Overriding and overloading

These are often confused in interviews.

Overriding Overloading
Where subclass redefines a superclass method same class, same name, different parameters
Signature identical name and parameters different parameter list
Decided at run time by the object's actual class at compile time by the argument types
Annotation write @Override none
class Printer {
    void print(int x)    { System.out.println("int " + x); }
    void print(String s) { System.out.println("String " + s); }     // overloads
}

Rules for overriding: same name and parameters; the return type must be the same or a subtype (covariant); the access cannot be weaker (a public method cannot become protected); it cannot throw broader checked exceptions; static, private and final methods cannot be overridden (a static method with the same signature hides rather than overrides). Always write @Override, so the compiler catches a mismatched signature.

Polymorphism and dynamic dispatch

Employee e = new Manager("Asha", 50000, 10000);   // upcast: a Manager held as an Employee
System.out.println(e.salary());                    // 60000.0, Manager's version is used

The variable's type (Employee) decides which methods can be called; the actual object (Manager) decides which version runs. This is dynamic dispatch. It is what lets you write:

double total(List<Employee> staff) {
    double sum = 0;
    for (Employee e : staff) sum += e.salary();    // each object uses its own salary()
    return sum;
}

Add a Director class tomorrow and total works without a single change. That is the point of polymorphism: code that depends on a general type is open to new subtypes.

Fields are not polymorphic: a field access uses the declared type. Keep fields private and use methods.

Casting and instanceof

An upcast is automatic and safe. A downcast needs an explicit cast and can fail with ClassCastException:

Employee e = new Manager("Asha", 50000, 10000);
Manager m = (Manager) e;            // OK here, but throws if e is not really a Manager

Check first. Since Java 16, pattern matching for instanceof checks and casts in one step:

if (e instanceof Manager m) {
    System.out.println("Manager with bonus: " + m.salary());
}

Since Java 21, pattern matching for switch works on types:

String describe(Object o) {
    return switch (o) {
        case Manager m  -> "manager " + m.name();
        case Employee x -> "employee " + x.name();
        case null       -> "nobody";
        default         -> "something else";
    };
}

Frequent type checks and downcasts usually mean the design should use polymorphism (put the behaviour in a method) instead.

final, abstract and sealed

  • final class cannot be extended (String, Integer); final method cannot be overridden; final variable cannot be reassigned.
  • abstract classes and methods must be completed by subclasses.
  • sealed (Java 17) restricts which classes may extend a type, giving a closed, known set:
public sealed interface Shape permits Circle, Rectangle {}
public record Circle(double r) implements Shape {}
public record Rectangle(double w, double h) implements Shape {}

double area(Shape s) {
    return switch (s) {                     // compiler checks every case is covered
        case Circle c    -> Math.PI * c.r() * c.r();
        case Rectangle r -> r.w() * r.h();
    };
}

If you add a new permitted type, every switch that misses it fails to compile: a safe way to model "one of these".

Composition over inheritance

Inheritance is the tightest coupling in Java: a subclass depends on its parent's internals, and a change in the parent can break it. A classic guideline says to use inheritance only for a real is-a relationship where the subclass honours everything the parent promises (the Liskov principle, in the SOLID lesson), and otherwise prefer composition ("has-a").

// Fragile: a Stack is not really a Vector, but inheriting exposes all of Vector's methods
class Stack<E> extends Vector<E> { ... }          // the famous example from the JDK

// Better: hold a list inside and expose only what you want
class OrderBook {
    private final List<Order> orders = new ArrayList<>();
    public void add(Order o) { orders.add(o); }
    public int count() { return orders.size(); }
}

Composition lets you change the internal list, delegate to several collaborators and test with fakes. Interfaces plus composition solve most problems; reserve inheritance for stable hierarchies.

Common mistakes

  • Using inheritance just to reuse code where there is no is-a relationship.
  • Confusing overloading with overriding.
  • Forgetting @Override.
  • Downcasting without checking (ClassCastException).
  • Calling an overridable method from a constructor, which may run in the subclass before its fields are set.
  • Deep hierarchies that nobody can follow.

Try it yourself

  1. Write Employee, Manager and Intern classes with different salary() rules and total a mixed list.
  2. Write two overloaded methods and one overridden method, and say for each whether Java chooses at compile or run time.
  3. Model Shape as a sealed interface with records and write an area switch; then add a new shape and read the compiler error.
  4. Replace an inheritance relationship you have written with composition.

Check yourself

What is the difference between overloading and overriding?

Overloading is several methods with the same name and different parameters in one class, resolved at compile time. Overriding is a subclass replacing an inherited method with the same signature, resolved at run time.

What is dynamic dispatch?

The JVM choosing which version of an overridden method to run based on the actual object's class at run time, not the variable's declared type.

Why use @Override?

It asks the compiler to verify that you really are overriding a method, catching typos and signature changes.

What is a sealed class for?

To restrict which classes can extend it, giving a closed set of subtypes that switch can check exhaustively.

Interview questions

What is polymorphism? Give an example.

The ability to treat different subclasses through a common supertype, with each providing its own behaviour. A List<Shape> can call area() on circles and rectangles, and each computes its own area at run time.

Why does Java not support multiple inheritance of classes?

To avoid ambiguity such as the diamond problem, where two parents provide the same member. Java allows multiple interfaces instead; default method conflicts must be resolved explicitly.

When do you prefer composition to inheritance?

When the relationship is has-a rather than is-a, when you want to change behaviour at run time or combine several behaviours, or when you do not want to depend on a parent's internals.

Summary

  • extends reuses a superclass; constructors chain with super(...).
  • Overriding is run-time and polymorphic; overloading is compile-time; always use @Override.
  • A variable's type decides what you can call; the object's class decides which version runs.
  • Use instanceof patterns, sealed types and exhaustive switch; favour composition over deep inheritance.

Going deeper

See how much of this you can explain

A free mock interview asks you new questions on Core Java: OOP, collections and exceptions for Java Full Stack Developer and scores every answer, with what to fix.