ProgrammingHardIBM · Deloitte pattern

What is printed?

What is printed?
class Vehicle {
    int wheels() { return 4; }
}
class Motorcycle extends Vehicle {
    @Override
    int wheels() { return 2; }
}
class Sidecar extends Motorcycle {
}
// in main:
Vehicle v = new Sidecar();
System.out.println(v.wheels());
  1. A. 4
  2. B. 2
  3. C. Compile-time error: Sidecar does not override wheels()
  4. D. 0

Correct answer: B. 2

Sidecar does not redeclare wheels(), so it simply inherits Motorcycle's override, which itself overrides Vehicle's. Dynamic dispatch on v (actually a Sidecar) finds the most-derived implementation in the chain, Motorcycle.wheels(), returning 2.

More OOP with C++ and Java questions

Exams that ask this topic