Bird
0
0

Identify the error in this Java code related to encapsulation:

medium📝 Debug Q6 of 15
Java - Encapsulation
Identify the error in this Java code related to encapsulation:
class User {
  private String password;
  public void setPassword(String password) {
    password = password;
  }
}
APassword variable should be public
BSetter does not update the class field correctly
CMissing getter method
DClass should be declared public
Step-by-Step Solution
Solution:
  1. Step 1: Analyze setter method

    Setter assigns parameter to itself, not to class field, so field remains unchanged.
  2. Step 2: Identify correct assignment

    Should use 'this.password = password;' to update the class field.
  3. Final Answer:

    Setter does not update the class field correctly -> Option B
  4. Quick Check:

    Setter must assign to class field using 'this' [OK]
Quick Trick: Use 'this' to assign parameter to class field in setter [OK]
Common Mistakes:
  • Assigning parameter to itself instead of class field
  • Making variables public to fix setter
  • Ignoring need for getter method

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes