ATHENA
Java Programming Essentials / Smart Reader
THE ATHENA LIBRARY

Java Programming Essentials

Miriam Okafor · textbook

Chapter 8 · Polymorphism

One call, many behaviours

Consider a List<Shape> containing a Circle, a Square and a Triangle. The loop for (Shape s : shapes) total += s.area(); never asks which kind of shape it holds. At runtime, the JVM selects the correct area() implementation for each object. This is dynamic dispatch, and it is the heart of polymorphism in Java.

The declared type (Shape) determines which methods the compiler allows us to call. The actual type of the object (Circle) determines which implementation runs. Keeping these two ideas separate explains nearly every polymorphism question you will meet in an exam.

Interfaces make the idea even more flexible. A Payable interface can be implemented by an Invoice and an Employee that share no parent class at all. Code written against Payable works with both — and with types that have not been written yet.

Write code against the general type, and let each object supply its own behaviour.

Fictional educational sample written for the Athena demo · Page 142 of 412.

100%saved