Bird
0
0

Find the problem in this code snippet related to data hiding:

medium📝 Debug Q7 of 15
Java - Encapsulation
Find the problem in this code snippet related to data hiding:
class Car {
  private int speed;
  public void setSpeed(int speed) {
    speed = speed;
  }
  public int getSpeed() {
    return speed;
  }
}
ANo problem, code works fine
BGetter should return parameter speed
CPrivate variable should be public
DSetter does not update the private variable
Step-by-Step Solution
Solution:
  1. Step 1: Check setter method

    Setter assigns parameter speed to itself, not to instance variable.
  2. Step 2: Correct usage

    Must use 'this.speed = speed;' to update private variable.
  3. Final Answer:

    Setter does not update the private variable -> Option D
  4. Quick Check:

    Setter must update instance variable [OK]
Quick Trick: Use 'this' to refer to instance variable in setters [OK]
Common Mistakes:
  • Assigning parameter to itself
  • Returning parameter in getter
  • Changing private to public

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes