ProgrammingHardIBM · Deloitte pattern

What is printed?

What is printed?
class Vehicle {
    void move() { System.out.print("Vehicle moves "); }
}
class Car extends Vehicle {
    @Override
    void move() { super.move(); System.out.print("Car drives "); }
}
class SportsCar extends Car {
    @Override
    void move() { super.move(); System.out.print("SportsCar speeds"); }
}
// in main:
Vehicle v = new SportsCar();
v.move();
  1. A. Vehicle moves Car drives SportsCar speeds
  2. B. SportsCar speeds Car drives Vehicle moves
  3. C. Vehicle moves SportsCar speeds Car drives
  4. D. SportsCar speeds Vehicle moves Car drives

Correct answer: A. Vehicle moves Car drives SportsCar speeds

v.move() dispatches virtually to SportsCar's override, which calls super.move() (Car's) FIRST before printing its own part; Car's override itself calls super.move() (Vehicle's) first. Unwinding: Vehicle's part prints first, then Car's, then SportsCar's own addition.

More OOP with C++ and Java questions

Exams that ask this topic