Bird
0
0

Identify the error in the following Java code snippet:

medium📝 Debug Q14 of 15
Java - Object-Oriented Programming Concepts
Identify the error in the following Java code snippet:
class Vehicle {
  private int speed;
  public int getSpeed() { return speed; }
}
class Car extends Vehicle {
  public void setSpeed(int speed) { this.speed = speed; }
}
ACannot access private field 'speed' directly in subclass
BCannot override getSpeed() method
CMissing constructor in Car class
DNo error, code is correct
Step-by-Step Solution
Solution:
  1. Step 1: Check access to private fields in subclass

    The field speed is private in Vehicle, so Car cannot access it directly.
  2. Step 2: Analyze the setSpeed method in Car

    Car's setSpeed tries to assign this.speed, which is not accessible, causing a compile error.
  3. Final Answer:

    Cannot access private field 'speed' directly in subclass -> Option A
  4. Quick Check:

    Private fields inaccessible in subclass [OK]
Quick Trick: Private fields are not visible in subclasses [OK]
Common Mistakes:
  • Assuming private fields are inherited
  • Ignoring access modifiers

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes