ProgrammingHardHCL · Tech Mahindra pattern

What is printed?

What is printed?
class Vehicle {
    void honk() { System.out.print("Beep "); }
}
class Car extends Vehicle {
    @Override
    void honk() { System.out.print("Honk "); }
}
class Truck extends Vehicle {
    @Override
    void honk() { System.out.print("HONK "); }
}
public class Main {
    static void test(Vehicle v) { v.honk(); }
    public static void main(String[] args) {
        java.util.List<Vehicle> fleet = java.util.List.of(new Car(), new Truck(), new Vehicle());
        for (Vehicle v : fleet) test(v);
    }
}
  1. A. Beep Beep Beep
  2. B. Honk HONK Beep
  3. C. Beep Honk HONK
  4. D. Compile-time error: List.of cannot mix different Vehicle subtypes

Correct answer: B. Honk HONK Beep

List.of(Car, Truck, Vehicle) is perfectly valid since all three are Vehicle (or a subtype). Each call to test(v) dispatches honk() dynamically to each element's actual class: Car prints Honk, Truck prints HONK, and the plain Vehicle prints Beep, in that iteration order.

More OOP with C++ and Java questions

Exams that ask this topic