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();- A. Vehicle-start beep
- B. Vehicle-start HONK
- C. Compilation error: honk must be declared in Vehicle as abstract
- 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
- What is printed? cpp struct Base { virtual void f() const { cout << "Base "; } }; struct Derived : Base { void f() const override { cout…
- What is printed? cpp struct Base { virtual Base clone() const { cout << "Base::clone "; return new Base(this); } }; struct Derived : Base…
- What is printed? java interface Greeter { String greet(); } class Main { public static void main(String[] args) { Greeter g = () -> "hi…
- What is printed? cpp struct Resource { virtual ~Resource() { cout << "~Resource "; } }; struct FileResource : Resource { ~FileResource() {…
- What is printed? cpp struct A { virtual void f() { cout << "A"; } }; struct B : virtual A { void f() override { cout << "B"; } }; struct C…
- What is printed? java class Node { Node next; int val; Node(int v) { val = v; } public String toString() { return val + (next != null ?…