skip to Main Content

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.
enter image description here

Every idea I seem to have either results in an error or doesn’t log anything to the console.

2

Answers


  1. Your super(balance) call does not have enough arguments. Therefore, the only argument being taken into account is the accountNumber. So instead of the object being constructed with this.balance = balance, it is constructed with this.balance = null or this.balance = NaN. You are also passing too many parameters to the SavingsAccount constructor. Fix it so it takes the parameters.

    SavingsAccount constructor:

    class SavingsAccount{
    var interestRate;
    constructor(num, name, bal, rate)
    {
        super(num, name, bal);
        this.interestRate = rate;
    
    }
    ...//other code here
    }
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search