Bird
0
0

Identify the problem in this Java code snippet:

medium📝 Debug Q6 of 15
Java - Encapsulation
Identify the problem in this Java code snippet:
class Account {
  private double balance;
  public void setBalance(double balance) {
    balance = balance;
  }
}
AThe balance variable should be declared public.
BThe method parameter shadows the instance variable, so assignment does nothing.
CThe setBalance method should return a value.
DThe balance variable is not initialized.
Step-by-Step Solution
Solution:
  1. Step 1: Understand variable shadowing

    The parameter 'balance' shadows the instance variable 'balance'.
  2. Step 2: Analyze assignment

    Assignment 'balance = balance;' assigns the parameter to itself, not the instance variable.
  3. Step 3: Correct approach

    Use this.balance = balance; to assign parameter to instance variable.
  4. Final Answer:

    The method parameter shadows the instance variable, so assignment does nothing. -> Option B
  5. Quick Check:

    Use 'this' to refer to instance variables [OK]
Quick Trick: Use 'this' to distinguish instance variables [OK]
Common Mistakes:
  • Ignoring variable shadowing
  • Assuming assignment updates instance variable

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes