Bird
0
0

You want to create a class BankAccount that remembers the balance for each account. Which design correctly uses instance fields to track the balance and safely update it?

hard🚀 Application Q15 of 15
C Sharp (C#) - Classes and Objects
You want to create a class BankAccount that remembers the balance for each account. Which design correctly uses instance fields to track the balance and safely update it?
class BankAccount {
  private decimal balance;

  public BankAccount(decimal initial) {
    balance = initial;
  }

  public void Deposit(decimal amount) {
    if (amount > 0) {
      balance += amount;
    }
  }

  public bool Withdraw(decimal amount) {
    if (amount > 0 && amount <= balance) {
      balance -= amount;
      return true;
    }
    return false;
  }

  public decimal GetBalance() {
    return balance;
  }
}
AIncorrect: Deposit and Withdraw should be static methods
BIncorrect: balance should be static to share across accounts
CCorrect design: instance field stores balance, methods update and read it safely
DIncorrect: balance should be public to allow direct access
Step-by-Step Solution
Solution:
  1. Step 1: Check if balance is instance field and encapsulated

    Balance is private instance field, unique per object, which is correct for tracking each account.
  2. Step 2: Verify methods safely update and provide access

    Deposit and Withdraw check amounts before changing balance, and GetBalance returns current balance safely.
  3. Final Answer:

    Correct design: instance field stores balance, methods update and read it safely -> Option C
  4. Quick Check:

    Instance field + safe methods = correct state management [OK]
Quick Trick: Use private instance fields with methods to control access [OK]
Common Mistakes:
MISTAKES
  • Making balance static, sharing state wrongly
  • Using static methods that can't access instance fields
  • Making balance public, breaking encapsulation

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More C Sharp (C#) Quizzes