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();
    }
}
  1. A. Vehicle-start Charging
  2. B. Silent-start Compile-time error: chargeBattery is not visible via Vehicle
  3. C. Silent-start Charging
  4. 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

Exams that ask this topic