ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
class Vehicle {
    void start() { System.out.print("Vehicle-start "); honk(); }
    void honk() { System.out.print("beep"); }
}
class Car extends Vehicle {
    @Override
    void honk() { System.out.print("HONK"); }
}
// in main:
Vehicle v = new Car();
v.start();
  1. A. Vehicle-start beep
  2. B. Vehicle-start HONK
  3. C. Compilation error: honk must be declared in Vehicle as abstract
  4. D. HONK

Correct answer: B. Vehicle-start HONK

Unlike C++ constructors, Java method dispatch inside start() is purely virtual regardless of where the call happens: since v's runtime object is a Car, the call to honk() inside start() dispatches to Car's override, printing HONK.

More OOP with C++ and Java questions

Exams that ask this topic