What will be the output of the following code? class Vehicle { public void…

2024

What will be the output of the following code? class Vehicle { public void move() { System.out.println("Vehicle is moving"); } } class Car extends Vehicle { public void move() { System.out.println("Car is moving"); } } public class Main { public static void main(String[] args) { Vehicle v = new Car(); v.move(); } }

  1. A.

    Runtime error

  2. B.

    Vehicle is moving / Vehicle is moving

  3. C.

    Compilation error

  4. D.

    Car is moving / Car is moving

  5. E.

    Question not attempted

Attempted by 229 students.

Show answer & explanation

Correct answer: D

In Java, when a subclass overrides a method from its superclass, the overridden method in the subclass is executed when the object is of the subclass type, even if the reference is of the superclass type. This is known as dynamic method dispatch.

In the given code, the Car class overrides the move() method from the Vehicle class. The object v is of type Car, but the reference is of type Vehicle. When v.move() is called, the move() method in the Car class is executed because the actual object is of type Car.

Therefore, the output will be: Car is moving.

Explore the full course: Up Lt Grade Assistant Teacher 2025