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.
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
- 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
Dog: Woof Cat: Meow Cow: Moo Animal: ...
Static type vs dynamic type
Child.greet overload(Parent) parent field
More examples
Payroll with polymorphism and pattern matching
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() > 0uses 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:
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
Prefer
Type checks must be updated for every new subclass; an overridden method extends automatically.
Downcasting without checking
Avoid
Prefer
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
- 1Build a Notification hierarchy (Email, Sms, Push) with a
send()method and send a list of mixed notifications. - 2Predict 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?