I tried creating a class BankAccount
in which another class SavingsAccount
extends it. I then created an instance of the class janesAccount
, called the deposit method and logged to the console its balance after any of the methods have been called (i.e deposit() or withdraw())
But instead of it to console.log 2000, it logs NaN instead.
Every idea I seem to have either results in an error or doesn’t log anything to the console.
>Solution :
As @Aralicia and @mykaf pointed out, your subclass SavingsAcccount
constructor is missing two parameters required by the superclass BankAccount
: accountNumber
and accountHolderName
, an so is the super()
call to the superclass constructor.
When you pass only the balance
, this argument is taken as the accountNumber
, but the constructor of BankAccount
expects 3 arguments and undefined
is passed instead, causing your bug.
Here’s a fixed and improved version of your code:
class BankAccount {
constructor(accountNumber, accountHolderName, balance) {
this.accountNumber = accountNumber;
this.accountHolderName = accountHolderName;
this.balance = balance;
}
deposit(amount) {
this.balance += amount;
}
withdraw(amount) {
this.balance -= amount;
}
getBalance() {
return this.balance;
}
}
class SavingsAccount extends BankAccount {
constructor(accountNumber, accountHolderName, balance, interestRate) {
super(accountNumber, accountHolderName, balance);
this.interestRate = interestRate;
}
calculateInterest() {
return this.getBalance() * (this.interestRate / 100);
}
}
const janesAccount = new SavingsAccount(123456, "Jane Doe", 1000, 0.05);
janesAccount.deposit(1000);
console.log(janesAccount.getBalance());
I made your OOP program a little bit more dynamic by adding an amount
parameter to deposit()
and withdraw()
methods to allow specifying different amounts for the operations.