Bird
0
0

Identify the error in this code related to data hiding:

medium📝 Debug Q14 of 15
Java - Encapsulation
Identify the error in this code related to data hiding:
class BankAccount {
  private double balance;
  public void setBalance(double balance) {
    balance = balance;
  }
  public double getBalance() {
    return balance;
  }
}
AThe setter method does not update the private variable
BThe getter method should be private
CThe balance variable should be public
DThe class should not have a setter method
Step-by-Step Solution
Solution:
  1. Step 1: Analyze setter method

    The setter uses balance = balance; which assigns the parameter to itself, not the class variable.
  2. Step 2: Identify correct assignment

    It should use this.balance = balance; to update the private variable.
  3. Final Answer:

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

    Setter must update class variable using 'this' [OK]
Quick Trick: Use 'this' to assign parameter to class variable [OK]
Common Mistakes:
  • Forgetting 'this' keyword in setter
  • Making getter private by mistake
  • Changing variable access to public unnecessarily

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes