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);
}
}- A. Beep Beep Beep
- B. Honk HONK Beep
- C. Beep Honk HONK
- 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
- What is printed? java List<String> strings = new ArrayList<>(); List<Integer> ints = new ArrayList<>()…
- What is printed? java class Holder<T extends Number> { T value; Holder(T v) { value = v; } double asDouble() { return value.doubleValue()…
- What is printed? java class Util { static <T> void swap(T[] arr, int i, int j) { T tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; } } public…
- What is printed? java public class Main { static <T extends Comparable<T>> T max(T a, T b) { return a.compareTo(b) >= 0 ? a : b; } public…
- Which statement is correct about this class? java public class Base { public void show() { } } class Sub extends Base { private void…
- Which statement is correct? java class Base { protected void configure() { } } class Derived extends Base { public void configure() { } }