Bird
0
0

Identify the issue in this Java class related to encapsulation:

medium📝 Debug Q7 of 15
Java - Encapsulation
Identify the issue in this Java class related to encapsulation:
class Product {
  private double price;
  public double getPrice() { return price; }
  public void setPrice(double price) { price = price; }
}
AThe class should not have setter methods
BThe getter method should be private
CThe variable price should be public
DThe setter method does not update the instance variable correctly
Step-by-Step Solution
Solution:
  1. Step 1: Review the setter method

    The setter method parameter price shadows the instance variable price. The assignment price = price; assigns the parameter to itself, not the instance variable.
  2. Step 2: Correct way to assign

    Use this.price = price; to assign the parameter value to the instance variable.
  3. Final Answer:

    The setter method does not update the instance variable correctly -> Option D
  4. Quick Check:

    Use 'this' to refer to instance variables [OK]
Quick Trick: Use 'this' to assign instance variables in setters [OK]
Common Mistakes:
  • Assigning parameter to itself in setter
  • Making getter private
  • Making variables public unnecessarily

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes