ProgrammingHardIBM · Deloitte pattern
What is printed?
What is printed?
class Vehicle {
void start() { System.out.print("Vehicle-start "); }
}
class ElectricCar extends Vehicle {
@Override
void start() { System.out.print("Silent-start "); }
void chargeBattery() { System.out.print("Charging "); }
}
public class Main {
public static void main(String[] args) {
Vehicle v = new ElectricCar();
v.start();
((ElectricCar) v).chargeBattery();
}
}- A. Vehicle-start Charging
- B. Silent-start Compile-time error: chargeBattery is not visible via Vehicle
- C. Silent-start Charging
- D. Compile-time error: cannot cast Vehicle to ElectricCar
Correct answer: C. Silent-start Charging
v.start() dispatches dynamically to ElectricCar's override, printing Silent-start. ((ElectricCar) v) is a valid downcast (the compiler allows it since ElectricCar is a subtype of Vehicle, and it succeeds at runtime because v genuinely holds an ElectricCar), exposing chargeBattery(), which prints Charging.
More OOP with C++ and Java questions
- What is printed? cpp struct Base { Base() { cout << "Base "; } }; struct Mixin1 { Mixin1() { cout << "Mixin1 "; } }; struct Mixin2 {…
- What is printed? java class Base { public String describe() { return "Base"; } } interface Describable { String describe(); } class Sub…
- What is printed? java class Resource { String name; Resource(String n) { name = n; System.out.print("open:" + n + " "); } void use() {…
- What is printed? cpp class Base { public: Base() { cout << "Base() "; } Base(int x) : Base() { cout << "Base(int) "; } }; int main() {…
- What is printed? java class Counter { int value; Counter(int v) { value = v; } Counter increment() { return new Counter(value + 1); }…
- What is printed? cpp struct Animal { virtual ~Animal() {} virtual void speak() const { cout << "..."; } }; struct Dog : Animal { void…