Bird
0
0

Identify the error in the following code related to encapsulation:

medium📝 Debug Q14 of 15
Java - Encapsulation

Identify the error in the following code related to encapsulation:

class BankAccount {
private double balance;
public void setBalance(double balance) {
balance = balance;
}
public double getBalance() {
return balance;
}
}
AThe balance variable should be public
BThe getter method should be private
CThe setter method does not update the class variable correctly
DThe setter method should return a value
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the setter method

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

    To update the class variable, use this.balance = balance; to refer to the instance variable.
  3. Final Answer:

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

    Use 'this' to assign parameter to instance variable [OK]
Quick Trick: Use 'this' to assign setter parameter to class variable [OK]
Common Mistakes:
  • Forgetting 'this' keyword in setter
  • Making getter private which breaks access
  • Expecting setter to return a value

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes