Java Programming

Inheritance, Polymorphism and Interfaces in Java

Beginner7 min readReviewed by on Updated

Polymorphism lets one call site work with many concrete types, and Java offers three tools to express it: class inheritance, abstract classes and interfaces. This guide explains how dynamic dispatch actually resolves a call, how to design interfaces with default and static methods, how sealed classes and pattern matching close a hierarchy safely, and why composition is usually the better way to reuse code.

What you will learn

  • Explain what happens at run time when an overridden method is called through a supertype reference
  • Decide between an abstract class and an interface for a given design
  • Use default, static and private interface methods without breaking implementors
  • Model a closed set of variants with sealed interfaces and exhaustive switch
  • Recognise when to favour composition over inheritance

Inheritance is the feature most closely associated with object-oriented programming, and the one most often misused. Its real payoff is not code reuse — composition does that better — but polymorphism: writing code against a general type and letting each concrete object supply its own behaviour. This guide covers the mechanics Java provides for that (class extension, abstract classes, interfaces), the modern additions that make hierarchies safer (sealed types and pattern matching), and the judgement calls about when to use each. Examples target Java 21.

Extending a class

class Manager extends Employee makes Manager a subclass that inherits every accessible field and method of Employee and can add or replace behaviour. A Manager is an Employee, so any code expecting an Employee accepts a Manager. Java permits a single superclass; every class without an explicit extends clause extends java.lang.Object.

public class Employee {
    private final String name;
    private final long monthlySalaryCents;

    public Employee(String name, long monthlySalaryCents) {
        this.name = name;
        this.monthlySalaryCents = monthlySalaryCents;
    }

    public long annualPayCents() {
        return monthlySalaryCents * 12;
    }

    public String name() { return name; }
}

public class Manager extends Employee {
    private final long bonusCents;

    public Manager(String name, long monthlySalaryCents, long bonusCents) {
        super(name, monthlySalaryCents);       // must run the superclass constructor first
        this.bonusCents = bonusCents;
    }

    @Override
    public long annualPayCents() {
        return super.annualPayCents() + bonusCents;   // reuse, then extend
    }
}

Three details of this code matter. The subclass constructor calls super(...) as its first statement; if you omit it, the compiler inserts super(), which fails to compile when the superclass has no no-argument constructor. The @Override annotation is optional but should be mandatory in your codebase: it turns a typo in the method name from a silent new method into a compile error. And private fields are inherited in the sense that they exist in the subclass object, but are not accessible from subclass code — Manager reaches the salary through the public method, not the field.

What final and protected mean here

Marking a class final forbids subclassing; marking a method final forbids overriding it. Use final on classes not designed for extension — which is most of them — because a class that can be extended has to promise that every method works when any other method is overridden. Effective designs either document exactly how to extend a class or forbid it.

protected members are visible to subclasses and to the same package. It is tempting to make fields protected so subclasses can use them directly, but that couples the subclass to the superclass's representation, so a later change to the field breaks every subclass. Prefer private fields with protected accessor methods if subclasses genuinely need the data.

Dynamic dispatch: how the call is resolved

The essential rule: the compiler checks the call against the static type of the reference; the run time picks the implementation by the actual class of the object.

Employee e = new Manager("Ada", 800_000, 2_000_000);
long pay = e.annualPayCents();    // compiles because Employee has the method
                                  // runs Manager's override: 11,600,000

The static type Employee decides which methods you may call. The dynamic type Manager decides which body runs. This is what lets a List<Employee> hold employees, managers and contractors and compute total payroll with one loop that never mentions a subclass.

Two things are not dispatched dynamically: fields and static methods. A field access e.someField is resolved by the static type, and a static method called through a reference resolves against the static type too (the compiler even warns about calling a static method via an instance). If you find yourself wanting to "override" a static method, you want an instance method.

Overriding has rules the compiler enforces. The override must have the same name and parameter types; its return type may be a subtype of the original (covariant return); it may not be less accessible than the original; and it may not declare broader checked exceptions. These rules exist so that any caller written against the superclass keeps working when handed a subclass.

Abstract classes

An abstract class cannot be instantiated and may declare abstract methods — signatures without bodies that concrete subclasses must implement. It is the right tool when several implementations share state and part of an algorithm but differ in specific steps:

public abstract class Report {
    private final String title;

    protected Report(String title) { this.title = title; }

    public final String render() {                // template: fixed skeleton
        return header() + "\n" + body() + "\n" + footer();
    }

    protected String header() { return "== " + title + " =="; }
    protected String footer() { return "-- end --"; }
    protected abstract String body();             // each subclass supplies this
}

public class SalesReport extends Report {
    private final long totalCents;

    public SalesReport(long totalCents) {
        super("Sales");
        this.totalCents = totalCents;
    }

    @Override
    protected String body() { return "Total: " + totalCents / 100.0; }
}

This is the Template Method pattern: the abstract class fixes the sequence and subclasses fill the gaps. Note the final on render() — the skeleton itself is not up for renegotiation.

Interfaces

An interface declares a contract — a set of method signatures — with no instance state. A class implements as many interfaces as it likes, which is Java's answer to multiple inheritance: you can inherit types from many sources, but implementation from only one superclass.

public interface Shape {
    double area();

    default String describe() {                   // default method: has a body
        return getClass().getSimpleName() + " with area " + area();
    }

    static Shape unitSquare() {                   // static method on the interface
        return new Rectangle(1, 1);
    }
}

public record Rectangle(double width, double height) implements Shape {
    @Override public double area() { return width * height; }
}

public record Circle(double radius) implements Shape {
    @Override public double area() { return Math.PI * radius * radius; }
}

Interface methods are implicitly public abstract; fields are implicitly public static final, so an interface is not a place to keep state. Since Java 8 an interface may also carry:

  • Default methods — implementations inherited by every implementor unless overridden. They exist so a widely implemented interface can gain a method without breaking existing classes; Collection.stream() and Iterable.forEach() were added this way.
  • Static methods — utility or factory methods scoped to the interface.
  • Private methods (Java 9) — helpers shared between default methods, invisible to implementors.

If a class inherits two default methods with the same signature from two interfaces, it does not compile until the class overrides the method itself; inside it can pick one with InterfaceName.super.method(). A method inherited from a superclass always wins over an interface default, which keeps existing class hierarchies stable when defaults are added.

Interface or abstract class?

InterfaceAbstract class
Instance fieldsNoYes
ConstructorsNoYes
Multiple inheritanceYes, any numberNo, single superclass
Method bodiesDefault, static, private onlyAny
Access levelsPublic (or private helpers)Any
ExpressesA capability or roleA partial implementation with shared state

Start with an interface. If several implementations turn out to share fields and code, add an abstract class that implements the interface and let those implementations extend it; other implementations can still implement the interface directly. This is how List and AbstractList relate in the JDK.

A marker interface has no methods at all and exists to tag a type — Serializable is the well-known example. Annotations have replaced most new uses of this idea, but you will meet it in existing code.

Sealed hierarchies and pattern matching

A traditional interface is open: anyone can implement it, so code that switches over "all the kinds of shape" can never be checked for completeness. Java 17 finalised sealed classes and interfaces, which name their permitted subtypes:

public sealed interface PaymentResult permits Approved, Declined, Pending {}
record Approved(String authorisationCode) implements PaymentResult {}
record Declined(String reason) implements PaymentResult {}
record Pending(java.time.Instant retryAfter) implements PaymentResult {}

Each permitted subtype must itself be final, sealed or explicitly non-sealed, and records are implicitly final, so this hierarchy is closed. Java 21's pattern matching for switch (JEP 441) then lets the compiler check exhaustiveness:

static String message(PaymentResult result) {
    return switch (result) {
        case Approved a -> "Approved, code " + a.authorisationCode();
        case Declined d -> "Declined: " + d.reason();
        case Pending p  -> "Pending until " + p.retryAfter();
        // no default needed: the compiler knows these are all the cases
    };
}

Add a fourth record to permits and every such switch fails to compile until it handles the new case. That is precisely the safety that a default branch would have thrown away. Record patterns (case Approved(String code) ->) deconstruct the components directly, and guards (case Declined d when d.reason().startsWith("fraud") ->) refine a case.

Sealed types shift some designs away from classic polymorphism. If behaviour varies per subtype and lives naturally on the subtype, use an overridden method. If the behaviour belongs to the consumer — serialisation, rendering, pricing rules that change more often than the types — a switch over a sealed hierarchy keeps that logic together without forcing every module's concern into the type.

Older instanceof checks followed by a cast have also been streamlined: if (obj instanceof Circle c) { ... c.radius() ... } binds the pattern variable in one step (Java 16).

Composition over inheritance

Inheritance couples a subclass to the implementation of its superclass, not just its interface. A change to a superclass method can break a subclass that depended on how it called other methods — the "fragile base class" problem. The cleaner way to reuse behaviour is composition: hold a reference to the object that has the behaviour and delegate to it.

// Inheritance: brittle. If HashSet.addAll is later changed to call add,
// or stops calling it, this count silently becomes wrong.
class CountingSet<E> extends HashSet<E> {
    private 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); }
}

// Composition: robust. Behaviour depends only on Set's public contract.
class CountingSet<E> implements Set<E> {
    private final Set<E> inner;
    private int added;
    CountingSet(Set<E> inner) { this.inner = inner; }
    @Override public boolean add(E e) { added++; return inner.add(e); }
    @Override public boolean addAll(Collection<? extends E> c) { added += c.size(); return inner.addAll(c); }
    // ... every other Set method forwards to inner
}

The composed version is more typing (an abstract forwarding class removes most of it) but it cannot be broken by internals of HashSet, works with any Set implementation, and can be tested with a fake. Use inheritance when there is a genuine is-a relationship and the superclass is designed for it; use composition for has-a and for reusing behaviour.

Common mistakes

Calling overridable methods from a constructor. The subclass override runs before the subclass's fields are initialised, so it reads defaults (null, 0). Constructors should call only private or final methods.

Breaking the contract of the superclass. An override that throws where the parent did not, ignores an argument the parent honoured or weakens a postcondition violates the Liskov substitution principle: callers written against the parent now break. If the subclass cannot honour the contract, it is not a subtype.

Deep hierarchies. Four levels of extends to share a few helper methods is a maintenance trap. Flatten with composition and interfaces.

Forgetting @Override. A misspelled method name (equal instead of equals) compiles as a brand-new method and your override never runs.

default branches on sealed switches. They compile, but they disable the exhaustiveness check that was the point of sealing.

Exposing protected fields. They lock the superclass's representation in place for every subclass in existence.

Confusing instanceof chains with design. A method that checks instanceof for five subtypes and branches is usually a missing polymorphic method — or, if the types are yours and closed, a sealed switch.

Key takeaways

  • Polymorphism means code written against a supertype works with any subtype; the run time picks the override by the object's actual class, while the compiler checks against the declared type.
  • Fields and static methods are not dispatched dynamically; only instance methods are.
  • Interfaces describe capabilities and support multiple inheritance of type; abstract classes share state and partial implementations. Start with an interface.
  • Default methods let interfaces evolve; a class must resolve conflicts between defaults explicitly.
  • Sealed interfaces plus pattern-matching switch give compiler-checked handling of a closed set of variants — leave out the default.
  • Reuse behaviour through composition and delegation; reserve inheritance for genuine is-a relationships with a superclass designed for extension.

Sources and further reading

Frequently asked questions

Should I use an abstract class or an interface?
Use an interface to describe a capability that unrelated classes can share; a class can implement many. Use an abstract class when implementations share state or a partial implementation that needs fields, constructors or non-public members. When in doubt, start with an interface — you can always add an abstract skeleton class beside it later.
Why does Java not support multiple class inheritance?
Two superclasses could supply conflicting fields and implementations with no clean rule for which wins. Java allows a class to implement any number of interfaces instead, and since Java 8 interfaces can carry default methods; conflicts between defaults must be resolved explicitly by the implementing class.
What is the difference between overriding and overloading?
Overriding replaces a superclass method with a subclass version that has the same signature and is chosen at run time by the object's actual class. Overloading declares several methods with the same name but different parameters in one class, and the compiler chooses between them at compile time using the argument types.
When should I use a sealed interface?
When the set of implementations is fixed by design and code elsewhere needs to handle every case — order states, expression nodes, result types. Sealing lets the compiler check that a switch covers all permitted subtypes, so adding a variant later produces compile errors exactly where handling is missing.