Bird
0
0

Identify the error in this Java code snippet:

medium📝 Debug Q6 of 15
Java - Object-Oriented Programming Concepts
Identify the error in this Java code snippet:
class Vehicle {
  void start() {
    System.out.println("Vehicle started");
  }
}
class Car extends Vehicle {
  void start() {
    System.out.println("Car started");
  }
}
public class Test {
  public static void main(String[] args) {
    Vehicle v = new Vehicle();
    v.start();
    Car c = new Vehicle();
    c.start();
  }
}
AVehicle class cannot be instantiated
BMethod start() is missing in Car class
CNo error, code runs fine
DCannot assign Vehicle object to Car reference
Step-by-Step Solution
Solution:
  1. Step 1: Check object assignments

    Vehicle v = new Vehicle(); is valid. But Car c = new Vehicle(); tries to assign a Vehicle object to a Car reference, which is invalid.
  2. Step 2: Understand type compatibility

    A subclass reference cannot point to a superclass object. This causes a compile-time error.
  3. Final Answer:

    Cannot assign Vehicle object to Car reference -> Option D
  4. Quick Check:

    Superclass object can't be assigned to subclass reference [OK]
Quick Trick: Subclass reference can't hold superclass object [OK]
Common Mistakes:
  • Confusing subclass and superclass assignments
  • Thinking method missing causes error here
  • Assuming Vehicle can't be instantiated

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes