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());- A. 4
- B. 2
- C. Compile-time error: Sidecar does not override wheels()
- 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
- 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 { default String hello() { return "Hi"; } } class Formal implements Greeter { @Override public…
- What is printed? cpp struct Base { Base() { cout << "Base-ctor "; } ~Base() { cout << "Base-dtor "; } }; struct Derived : Base { Derived()…
- What is printed? java public class Main { static int risky() { try { return 1; } finally { return 2; } } public static void main(String[]…
- What is printed? java class MyChecked extends Exception { MyChecked(String m) { super(m); } } public class Main { static void risky()…
- Which statement about this code is correct? java class Main { static void risky() { if (Math.random() < 2) throw new…