Bank account and savings account
HardClasses20 min
Write a class BankAccount and its subclass SavingsAccount.
BankAccount:
- Constructor:
new BankAccount(owner, balance).owneris a string,balanceis a number that is 0 or more. Ifbalanceis not passed, it is0. - A getter
ownerreturns the owner, a getterbalancereturns the current balance. - There is no setter for
balance:account.balance = 500must not change the balance. Onlydepositandwithdrawchange it. - The method
deposit(amount)addsamountto the balance and returns the new balance. withdraw(amount)takesamountfrom the balance and returns the new balance. You can take the whole balance (the result is0). Ifamountis greater than the balance, thrownew Error('Insufficient funds'). It is a plainErrorobject, not aRangeErrorand not a string.- If
amountis0or negative,depositandwithdrawthrow aRangeError(any message). - When a method throws, the balance stays the same.
SavingsAccount:
- It inherits from
BankAccountwithextends. Constructor:new SavingsAccount(owner, balance, rate), whererateis a percent, 0 or more (for example5means 5%). Call the parent constructor with super. owner,balance,depositandwithdrawcome fromBankAccount. Do not write them again inSavingsAccount.addInterest()addsbalance * rate / 100to the balance (not rounded) and returns the new balance. If this interest is0(rate 0 or balance 0), the balance stays the same and there is no error.
Every account keeps its own balance: a change in one account does not change another.
Examples
new BankAccount('Ann', 100).deposit(50)Returns 150
new BankAccount('Bob').balanceReturns 0
new SavingsAccount('Kate', 1000, 5).addInterest()Returns 1050
Loading the editor...
- The constructor stores the owner and the balance, the default balance is 0
- deposit and withdraw return the new balance
- Taking more than the balance throws Insufficient funds
- SavingsAccount is a BankAccount and adds interest
Hidden tests run on Submit