Bird
0
0

Identify the error in the following Java code snippet:

medium📝 Debug Q14 of 15
Java - Encapsulation
Identify the error in the following Java code snippet:
class Car {
  private int speed;
  public void setSpeed(int speed) {
    speed = speed;
  }
  public int getSpeed() {
    return speed;
  }
}
AThe setter method does not update the private variable
BThe private variable speed should be public
CThe getter method should return void
DThe class Car should be declared public
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the setter method

    The setter method assigns the parameter speed to itself, not to the private variable.
  2. Step 2: Understand variable shadowing

    The parameter speed shadows the private variable. To update the private variable, use this.speed = speed;.
  3. Final Answer:

    The setter method does not update the private variable -> Option A
  4. Quick Check:

    Use 'this' to update private variable in setter [OK]
Quick Trick: Use 'this.' to refer to class variable in setters [OK]
Common Mistakes:
  • Not using 'this' keyword in setter
  • Making private variable public unnecessarily
  • Changing getter return type incorrectly

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes