Skip to content
Ameen Abozaid
BEG-023

Polymorphism

  • 5 Lessons
  • 58 min of reading
  • 3 h practice (estimate)
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

  1. Explain dynamic dispatch and predict which method runs for a given reference and object type.
  2. Use a superclass or interface reference to treat different objects uniformly.
  3. Replace a type-checking if/switch chain with polymorphic method calls.

Lessons

  1. 01One call, many behaviors12 min read
  2. 02Upcasting, downcasting, and instanceof11 min read
  3. 03Dynamic dispatch under the hood (conceptual)12 min read
  4. 04Replacing conditionals with polymorphism12 min read
  5. 05Demo: month-end processing without a single type check11 min read

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)

IDOutcomeTask
BEG-023-EX011Animal a = new Dog(); a.speak(); where Dog overrides speak. Which runs and why?
BEG-023-EX022Put a Dog, Cat, and Cow in a List<Animal> and call speak() on each.
BEG-023-EX032Explain why Animal a = new Dog(); a.fetch(); does not compile when only Dog has fetch().
BEG-023-EX043Refactor if (shape.type.equals("CIRCLE")) ... else if (...) area code into polymorphism.
BEG-023-EX051Predict: Animal a = new Cat(); Dog d = (Dog) a; What happens?
BEG-023-EX061, 2Predict the output of the eight snippets in the "predict the output" quiz.
Show solutions
  • EX01 Dog.speak runs: 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 no fetch. Use instanceof Dog d and d.fetch() or add it to the parent if it truly belongs.
  • EX04 Add abstract double area() (or a normal method) to Shape; Circle and Square override it; callers use shape.area().
  • EX05 Compiles, then throws ClassCastException at 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.

  1. 1A x = new B(); System.out.println(x.who()); prints:O1
  2. 2A x = new A(); System.out.println(x.who()); prints:O1
  3. 3B y = (B) new A(); results in:O1
  4. 4Which is resolved at run time?O1
  5. 5List<A> list = List.of(new A(), new B()); then a loop calling who() prints:O2
  6. 6Upcasting A x = new B(); is:O2
  7. 7Through a parent reference you can call:O2
  8. 8The best fix for repeated if (x instanceof ...) chains is:O3
  9. 9After the refactor, adding a new account type needs:O3
  10. 10Downcasting safely requires:O1

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).

Type to search levels, phases, modules and lessons.