Computer Science I / Modular Decomposition and Reuse
Practice question · Fill in the blanks

SavingsAccount extends Account and overrides applyMonthly(). A variable declared as Account is holding a SavingsAccount. Complete the sentence.

Calling applyMonthly() on that variable runs ______.

Word bank: SavingsAccount's body, chosen at run time from the object · Account's body, chosen at compile time from the declared type · Account's body, because the variable was declared as Account · neither body, because the override makes the call ambiguous

Hints
  1. The body is chosen from the object in front of you, not from the type written in the source.
  2. The declared type decides which methods you may call, not which body answers.
Show the answer

Calling applyMonthly() on that variable runs SavingsAccount's body, chosen at run time from the object.

Why

Dynamic dispatch selects the body from the object's actual class, so SavingsAccount's version runs even though the variable is declared Account. The declared type governs only which calls are permitted. Choosing on the declared type is the classic error, it would make polymorphism impossible, since the whole point is that one call site serves many classes.

Read the lesson: Modular Decomposition and Reuse →

Practise Modular Decomposition and Reuse

The app has 6 more questions on this lesson, and keeps your place in the course. Computer Science I is free to start.

More questions on Modular Decomposition and Reuse