Polymorphism
On this page 8 topics
Overview
Topics
- Dynamic dispatch
- upcasting
- interfaces
- abstraction
Learn first
58 min of reading · 3 h of practice (estimate)
Learning outcomes
- Explain dynamic dispatch and predict which method runs for a given reference and object type.
- Use a superclass or interface reference to treat different objects uniformly.
- Replace a type-checking
if/switchchain with polymorphic method calls.
Lessons
Lab and exercises
Lab
BEG-023-LAB1 · Month-end processing
Outcomes: 1, 2, 3 · Time: ~2 h Apply month-end rules to a mixed list of accounts (savings: interest, checking: fee) with a single loop and no type checks. Then add a third account type. Acceptance: adding a new account type requires no change to the loop.
Exercises (assessment: "predict the output" quiz on 8 snippets)
| ID | Outcome | Task |
|---|---|---|
| BEG-023-EX01 | 1 | Animal a = new Dog(); a.speak(); where Dog overrides speak. Which runs and why? |
| BEG-023-EX02 | 2 | Put a Dog, Cat, and Cow in a List<Animal> and call speak() on each. |
| BEG-023-EX03 | 2 | Explain why Animal a = new Dog(); a.fetch(); does not compile when only Dog has fetch(). |
| BEG-023-EX04 | 3 | Refactor if (shape.type.equals("CIRCLE")) ... else if (...) area code into polymorphism. |
| BEG-023-EX05 | 1 | Predict: Animal a = new Cat(); Dog d = (Dog) a; What happens? |
| BEG-023-EX06 | 1, 2 | Predict the output of the eight snippets in the "predict the output" quiz. |
Show solutions
- EX01
Dog.speakruns: the method is chosen by the real object at run time. - EX02
for (Animal x : animals) x.speak();each prints its own sound. - EX03 The compiler checks the reference type
Animal, which has nofetch. Useinstanceof Dog dandd.fetch()or add it to the parent if it truly belongs. - EX04 Add
abstract double area()(or a normal method) toShape;CircleandSquareoverride it; callers useshape.area(). - EX05 Compiles, then throws
ClassCastExceptionat run time. - EX06 Answers for the eight snippets are given by the instructor; apply the reference-type-checks, object-type-runs rule. Pass at least six.
Quiz
Outcomes: O1 dynamic dispatch · O2 uniform treatment through a parent type · O3 replacing type checks. Setup for Q01-Q06: class A { String who() { return "A"; } }, class B extends A { @Override String who() { return "B"; } }.
A self-check for you: nothing is graded, saved or sent anywhere. Choose an answer, then check it. You can try again as often as you like.
Practical part
The eight "predict the output" snippets are Q01-Q06 above plus the two below, exercises BEG-023-EX01 to EX06, and the month-end lab. Pass: at least six of eight snippets correct and the lab acceptance met.
Snippet 7 (same A and B as above, plus class C extends B {}): A x = new C(); System.out.println(x.who()); prints: A. A B. B C. C D. Compile error. (Answer: B. C inherits B's override, so dynamic dispatch picks B.who().)
Snippet 8 (same A and B): A[] items = { new B(), new A(), new B() }; String s = ""; for (A a : items) s += a.who(); System.out.println(s); prints: A. AAA B. BAB C. BBB D. ABA. (Answer: B. Each element's real type decides which who() runs.)
Common mistakes
Downcasting everywhere; confusing overloading with overriding.
Assessment
"predict the output" quiz on 8 snippets.
Career relevance
Strategy pattern (JNR-005) and dependency inversion (JNR-004).