ProgrammingHardIBM · Deloitte pattern
What is printed?
What is printed?
class Vehicle {
void move() { System.out.print("Vehicle moves "); }
}
class Car extends Vehicle {
@Override
void move() { super.move(); System.out.print("Car drives "); }
}
class SportsCar extends Car {
@Override
void move() { super.move(); System.out.print("SportsCar speeds"); }
}
// in main:
Vehicle v = new SportsCar();
v.move();- A. Vehicle moves Car drives SportsCar speeds
- B. SportsCar speeds Car drives Vehicle moves
- C. Vehicle moves SportsCar speeds Car drives
- D. SportsCar speeds Vehicle moves Car drives
Correct answer: A. Vehicle moves Car drives SportsCar speeds
v.move() dispatches virtually to SportsCar's override, which calls super.move() (Car's) FIRST before printing its own part; Car's override itself calls super.move() (Vehicle's) first. Unwinding: Vehicle's part prints first, then Car's, then SportsCar's own addition.
More OOP with C++ and Java questions
- What is printed? java class Animal { String category() { return "Animal"; } } class Mammal extends Animal { @Override String category() {…
- What is printed? java class Shape { double area() { return 0; } @Override public String toString() { return getClass().getSimpleName() +…
- What is printed? cpp class Base { public: Base() { cout << "Base "; } Base& operator=(const Base&) { cout << "Base= "; return this; } }…
- What is printed? cpp struct Base { Base() { cout << "B "; } virtual ~Base() { cout << "~B "; } }; struct Derived : Base { int data…
- What is printed? java class Converter<T, R> { R convert(T input, java.util.function.Function<T, R> fn) { return fn.apply(input); } } // in…
- What is printed? cpp template<typename T> T maxVal(T a, T b) { return a > b ? a : b; } class Money { int cents; public: Money(int c)…