Bird
0
0

Given these classes:

hard📝 Application Q15 of 15
Java - Polymorphism
Given these classes:
class Vehicle {
  void start() { System.out.println("Vehicle starts"); }
}
class Car extends Vehicle {
  void start() { System.out.println("Car starts"); }
}
class Bike extends Vehicle {
  void start() { System.out.println("Bike starts"); }
}
public class Test {
  public static void main(String[] args) {
    Vehicle[] vehicles = {new Car(), new Bike(), new Vehicle()};
    for (Vehicle v : vehicles) {
      v.start();
    }
  }
}

What is the output when this program runs?
AVehicle starts Vehicle starts Vehicle starts
BCompilation error due to array initialization
CCar starts Vehicle starts Bike starts
DCar starts Bike starts Vehicle starts
Step-by-Step Solution
Solution:
  1. Step 1: Analyze array elements and their types

    Array holds objects: Car, Bike, Vehicle, all as Vehicle references.
  2. Step 2: Understand method calls in loop

    Each start() call runs overridden method of actual object type due to runtime polymorphism.
  3. Step 3: Determine output lines

    Car prints "Car starts", Bike prints "Bike starts", Vehicle prints "Vehicle starts" in order.
  4. Final Answer:

    Car starts Bike starts Vehicle starts -> Option D
  5. Quick Check:

    Overridden methods run per object type in array [OK]
Quick Trick: Loop calls overridden methods based on actual object type [OK]
Common Mistakes:
  • Expecting all calls to run Vehicle's method
  • Confusing array reference type with object type
  • Thinking array initialization causes error

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes