Skip to main content
๐Ÿ“œ WAYPOINT LESSON

Polymorphic collections

โญโญโญ advancedโณ 10 min read๐Ÿ“ Lesson 195 of 256

One row per element: reference type, object type, which override runs, contribution โ€” and the cast trap.

Polymorphic collections. ArrayList<Employee> holds any mix of Employees and Managers; the enhanced for-loop calls the override for whatever each element really is:

int total = 0;
for (Employee e : staff) {
    total += e.pay();   // Manager? +bonus. Employee? base.
}

The tracing discipline for these: one row per element, columns for "reference type / object type / which pay runs / contribution." The hard version adds a conditional override โ€” a Manager only counts the bonus when a flag holds โ€” so the contribution column depends on state you must also trace.

And the cast trap: ((Manager) e).bonus compiles but throws ClassCastException when e holds a plain Employee. On the exam, "runtime error" is a possible answer, not a distraction โ€” check whether every element really is the cast type before trusting any option that casts.

โšก Now practice

Ready to Code
Polymorphism gauntletDispatch, abstract references, and inherited-method dispatch, each with traps.
3 challenges ยท ยท ~60 min