Polymorphism
Lesson 14 of 20One call, many bodies — watch dynamic dispatch pick the right override at runtime, not compile time.
Same call, different behavior
Polymorphism means one method call can run different bodies — the OBJECT, not the variable, decides at runtime.
Overriding
A subclass rewrites an inherited method with the same signature — the new body wins.
Dynamic dispatch
At runtime the JVM asks the real object which override to run. That choice is polymorphism.
Parent variables, child objects
Shape s = new Circle() is legal: the variable type is the parent, the object is the child.
Why it helps
One loop can drive a whole zoo of objects — each responds in its own way, no if-chains.
A Shape variable holding a Circle
The compiler checks the variable type; the JVM trusts the object type when the call runs.
1public class ShapeDemo {2public static void main(String[] args) {3Shape s = new Circle();4s.draw();5}6}78class Shape {9void draw() {10System.out.println("A shape");11}12}1314class Circle extends Shape {15void draw() {16System.out.println("A circle");17}18}
Two classes, one method name: Shape declares draw(), Circle overrides it with its own body.
Dynamic dispatch, step by step
Compile time picks what you may call; runtime picks which body actually runs.
A zoo of overrides
Both variables are typed Animal — what actually comes out?
1public class AnimalDemo {2public static void main(String[] args) {3Animal a = new Dog();4Animal b = new Cat();5a.speak();6b.speak();7}8}9class Animal {10void speak() { System.out.println("..."); }11}12class Dog extends Animal {13void speak() { System.out.println("Woof"); }14}15class Cat extends Animal {16void speak() { System.out.println("Meow"); }17}
Hint: The variable type decides what you may call; the object type decides which override actually runs.
Polymorphism vocabulary
Click a term, then click its meaning.
Key takeaways
Overriding = same signature in the subclass; the new body replaces the old one.
Dynamic dispatch chooses by object type, decided fresh on every single call.
A parent-type variable can hold any child-type object.
@Override is optional but catches typos at compile time — use it.
Polymorphism lets one loop or one method handle a whole family of types.