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), andgetBalance()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 returnsTrueon success; otherwise it leaves the balance unchanged and returnsFalse.getBalance()returns the current balance.- Invalid amounts (
0or negative) must raise an error (ValueErrorin 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