Facebook Pixel

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.

CommandBehaviorOutput
["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.

Example
Input
7
open savings s1
open checking c1
deposit s1 200
withdraw s1 300
withdraw c1 150
withdraw c1 50
balance c1
Output
Opened savings s1
Opened checking c1
s1 balance 200
s1 insufficient
c1 over limit
c1 balance -50
c1 balance -50
Explanation
Opening both accounts starts them at balance 0. Depositing 200 into s1 raises it to 200. Withdrawing 300 from s1 would go negative, so savings rejects it with "insufficient". Withdrawing 150 from c1 (starting at 0) would reach -150, which is below the -100 floor, so checking rejects it with "over limit". Withdrawing 50 from c1 reaches -50, which is within the limit, so it succeeds. The final `balance` confirms -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.

Invest in Yourself
Your new job is waiting. 83% of people that complete the program get a job offer. Unlock unlimited access to all content and features.
Go Pro