Exercise: Inheritance
This exercise puts the inheritance lesson into code.
Scenario
Model a bank account system with two account types. A base Account class holds the balance
and handles deposits and balance queries for both types. SavingsAccount and CheckingAccount
each extend it and override only withdraw, which is where the two types actually differ.
Accounts are identified by string ids and are created on demand via an open command. Each
command produces exactly one output line.
Commands
The program reads one command per line and prints one line of output per command.
| Command | Behavior | Output |
|---|---|---|
["open", type, id] | Create a new account of type savings or checking | "Opened <type> <id>" |
["deposit", id, amount] | Add amount to the named account | "<id> balance <bal>", or "<id> not found" if the id does not exist |
["withdraw", id, amount] | Attempt a withdrawal (see rules below) | see below, or "<id> not found" if the id does not exist |
["balance", id] | Report current balance | "<id> balance <bal>", or "<id> not found" if the id does not exist |
Withdrawal rules differ by type. A savings account rejects any withdrawal that would make the
balance negative, returning "<id> insufficient". A checking account permits overdrafts down
to a floor of -100; if the result would fall below -100 it returns "<id> over limit",
otherwise it subtracts and returns "<id> balance <bal>". New accounts start at 0. Amounts
are integers.
7 open savings s1 open checking c1 deposit s1 200 withdraw s1 300 withdraw c1 150 withdraw c1 50 balance c1
Opened savings s1 Opened checking c1 s1 balance 200 s1 insufficient c1 over limit c1 balance -50 c1 balance -50
Your task
Create the two account subclasses below the Account base class in the editor: SavingsAccount(Account) and CheckingAccount(Account), each overriding only withdraw with the policy described above. Do not modify Account or run_accounts.