A parent method calling an overridden method
PirateGreeter changed one small step; Greeter's greet() picked it up automatically.
Polymorphism means one variable type can hold objects of many classes, and a method call runs the version that belongs to the actual object. The JVM does this with dynamic dispatch, using per-class method tables (vtables) that the JIT then optimises away when it can.
Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Model Employee with pay() returning a base salary, and subclasses Intern (half pay) and Contractor (hourly × hours). Compute the total payroll for a mixed list.
Predict, then verify: class P { void hi() { System.out.println("P"); } void run() { hi(); } }, class Q extends P { void hi() { System.out.println("Q"); } }, calling new Q().run() and new P().run().
Write a Notifier base class with send(String) and two subclasses. Write a static method broadcast(List<Notifier>, String) that never mentions the subclasses.
Explain it without notes
Explain the difference between a variable's declared type and its object's runtime class, and what each one controls.
What is dynamic dispatch and which bytecode instructions perform it?
How does a vtable make virtual calls fast?
Which members are NOT polymorphic in Java?
Why can a megamorphic call site be slower than a monomorphic one?
Expected output
Greeter: Hello, Sam!
PirateGreeter: Ahoy, Sam!
ShyGreeter: ...hi Sam