Skip to main content
All questions
MediumOOP · Encapsulation

Bank Account Encapsulation

Written by a community member · · 4 attempts · 50% pass

1

Implement a BankAccount class that demonstrates encapsulation with business rules.

Requirements:

  • The constructor accepts an account holder name and an optional starting balance.
  • The balance must be internal/private state.
  • Provide deposit(amount), withdraw(amount), and getBalance() methods.
  • deposit(amount) increases the balance by a positive amount and returns the updated balance.
  • withdraw(amount) decreases the balance by a positive amount only if sufficient funds exist; it returns True on success; otherwise it leaves the balance unchanged and returns False.
  • getBalance() returns the current balance.
  • Invalid amounts (0 or negative) must raise an error (ValueError in Python).
  • The starting balance must also be non-negative.

Examples:

alice = BankAccount("Alice", 500)
alice.withdraw(150)  # True
alice.getBalance()   # 350
acct = BankAccount("Ben", 100)
acct.withdraw(150)  # False, balance stays 100