Skip to content

Module 6 · Inheritance, Polymorphism and Interfaces — topic 2 of 3

Polymorphism

One interface, many implementations: upcasting, dynamic method dispatch, instanceof with pattern matching, downcasting safely, and overloading versus overriding.

Beginner 16 min read·Lesson 21 of 39 in Java Programming

Learning objectives

  • Write code that works with a superclass type but runs subclass behaviour
  • Explain dynamic dispatch and the difference between static and dynamic types
  • Use instanceof pattern matching and safe downcasting

Definition

Polymorphism is the ability of a single reference type to refer to objects of different subclasses and have the correct overridden method chosen at run time, based on the object's actual class (dynamic dispatch).

Introduction

A drawing program might hold a list of shapes and call draw() on each one. It doesn't need to know whether a shape is a circle or a square — each object knows how to draw itself. This is polymorphism: the same call, different behaviour, decided by the object at run time.

Why it matters

Polymorphism lets you add new types (a Triangle) without changing the code that uses them — the open/closed principle.

Collections, frameworks and design patterns such as Strategy and Template Method all depend on it.

Detailed explanation

Upcasting. A subclass object can be assigned to a superclass variable: Shape s = new Circle(2);. This is always safe and needs no cast.

Static and dynamic types. The *static* (declared) type of s is Shape; its *dynamic* (run-time) type is Circle. The compiler uses the static type to decide which methods you may call; the JVM uses the dynamic type to decide which override runs.

Dynamic dispatch. s.area() runs Circle.area() because the object is a Circle. This applies to overridden instance methods only — fields, static methods and private methods are not polymorphic.

Overloading vs overriding. Overloading (same name, different parameters) is chosen at compile time from static types. Overriding (same signature in a subclass) is chosen at run time from the dynamic type.

instanceof and pattern matching. obj instanceof Circle tests the dynamic type. Since Java 16, if (obj instanceof Circle c) tests and casts in one step, binding the variable c.

Downcasting. (Circle) s converts back to the subclass type. If the object isn't really a Circle, a ClassCastException is thrown, so test with instanceof first — or, better, design the superclass so that you rarely need to downcast.

Syntax

Java
Shape s = new Circle(2); // upcast
double a = s.area(); // Circle.area() runs: dynamic dispatch
if (s instanceof Circle c) { // Java 16+ pattern matching
System.out.println(c.radius());
}
Circle c2 = (Circle) s; // downcast (ClassCastException if wrong)
  • The compiler only allows calls the declared type supports.
  • Fields are resolved by static type — avoid public fields in hierarchies.
  • Prefer overriding to chains of instanceof checks.

Code examples

One loop, many behaviours

Java
public class Main {
public static void main(String[] args) {
Animal[] zoo = {new Dog(), new Cat(), new Cow(), 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"; }
}
class Cow extends Animal {
@Override String sound() { return "Moo"; }
}
Output
Dog: Woof
Cat: Meow
Cow: Moo
Animal: ...

Static type vs dynamic type

Java
public class Main {
static String describe(Parent p) { return "overload(Parent)"; }
static String describe(Child c) { return "overload(Child)"; }
public static void main(String[] args) {
Parent p = new Child();
System.out.println(p.greet()); // dynamic dispatch: Child's override
System.out.println(describe(p)); // overload chosen by static type
System.out.println(p.name); // fields are not polymorphic
}
}
class Parent {
String name = "parent field";
String greet() { return "Parent.greet"; }
}
class Child extends Parent {
String name = "child field";
@Override String greet() { return "Child.greet"; }
}
Output
Child.greet
overload(Parent)
parent field

More examples

Payroll with polymorphism and pattern matching

Java
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Employee> staff = List.of(new Salaried("Asha", 600_000), new Hourly("Ravi", 250, 170), new Intern("Meera", 15_000));
long total = 0;
for (Employee e : staff) {
long pay = e.monthlyPay();
total += pay;
String extra = "";
if (e instanceof Hourly h && h.overtimeHours() > 0) extra = " (" + h.overtimeHours() + "h overtime)";
System.out.printf("%-6s %-9s %8d%s%n", e.name, e.getClass().getSimpleName(), pay, extra);
}
System.out.println("Total payroll: " + total);
Employee first = staff.get(0);
try {
Hourly wrong = (Hourly) first;
} catch (ClassCastException ex) {
System.out.println("Cannot treat " + first.name + " as Hourly");
}
}
}
abstract class Employee {
final String name;
Employee(String name) { this.name = name; }
abstract long monthlyPay();
}
class Salaried extends Employee {
private final long annual;
Salaried(String name, long annual) { super(name); this.annual = annual; }
@Override long monthlyPay() { return annual / 12; }
}
class Hourly extends Employee {
private final long rate;
private final int hours;
Hourly(String name, long rate, int hours) { super(name); this.rate = rate; this.hours = hours; }
int overtimeHours() { return Math.max(0, hours - 160); }
@Override long monthlyPay() { return rate * Math.min(hours, 160) + Math.round(rate * 1.5 * overtimeHours()); }
}
class Intern extends Employee {
private final long stipend;
Intern(String name, long stipend) { super(name); this.stipend = stipend; }
@Override long monthlyPay() { return stipend; }
}
Output
Asha   Salaried     50000
Ravi   Hourly       43750 (10h overtime)
Meera  Intern       15000
Total payroll: 108750
Cannot treat Asha as Hourly

Step-by-step explanation

  • The list's element type is the abstract Employee; each element is a different concrete subclass.
  • e.monthlyPay() dispatches to the right override for each object — the loop never checks types to compute pay.
  • e instanceof Hourly h && h.overtimeHours() > 0 uses pattern matching to test, cast and use the variable in one condition.
  • Ravi's pay is 250 × 160 + 250 × 1.5 × 10 = 40,000 + 3,750 = 43,750.
  • Casting a Salaried object to Hourly compiles (they share a superclass) but fails at run time with ClassCastException.

Expected output

Running “Payroll with polymorphism and pattern matching” prints exactly:

TextOutput
Asha Salaried 50000
Ravi Hourly 43750 (10h overtime)
Meera Intern 15000
Total payroll: 108750
Cannot treat Asha as Hourly

Practical applications

  • Processing a mixed list of payment methods through one interface
  • Plugins and strategies chosen at run time
  • GUI event handlers: every button has its own onClick behaviour
  • Collections such as List referring to ArrayList or LinkedList

Best practices

  • Program to the most general type that offers what you need (List, Shape, Employee).
  • Put behaviour that varies by type in overridden methods.
  • Use instanceof pattern matching when a type check is genuinely necessary.

Common mistakes

Replacing overriding with instanceof chains

Avoid

if (s instanceof Circle) ... else if (s instanceof Square) ...

Prefer

double a = s.area(); // each subclass overrides area()

Type checks must be updated for every new subclass; an overridden method extends automatically.

Downcasting without checking

Avoid

Dog d = (Dog) animal;

Prefer

if (animal instanceof Dog d) { d.fetch(); }

If animal isn't actually a Dog, the cast throws ClassCastException at run time.

Important notes

  • Java 21 adds pattern matching in switch: switch (shape) { case Circle c -> ...; case Square s -> ...; }, which is exhaustive for sealed hierarchies.
  • Constructors are never polymorphic, and calling an overridable method from a constructor runs the subclass version before the subclass is initialised.

Key takeaways

  • A superclass reference can hold any subclass object.
  • Overridden methods are chosen at run time by the object's real class; overloads at compile time.
  • Check with instanceof (pattern matching) before downcasting.

Try it yourself

  1. 1
    Build a Notification hierarchy (Email, Sms, Push) with a send() method and send a list of mixed notifications.
  2. 2
    Predict and then verify the output when a superclass method calls an overridden method.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

8 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
  • BeginnerWhat happens? `Object o = "text"; Integer i = (Integer) o;`
  • BeginnerWhen is an overridden method chosen?
Practise this topic