Inheritance and Overriding

Inheritance and Overriding

In this exercise we are going to create a class from which we are going to inherit and use its properties and methods and we will also override the method from the child class

1) let's create the parent class

 import { AccountType } from './enums';

export class BankAccount {
    private _balance = 0;
    id:number;
    title : string;
    accountType : AccountType;

    constructor(accuntSettings : any) {
        console.log("constructor BankAccount");
        this.id = accuntSettings.id;
        this.title = accuntSettings.title;
        this._balance = accuntSettings.balance;
    } 

    //get set balance
    public get balance() : number {
        return this._balance;
    }
    public set balance(value : number) {
        this._balance = value;
    }
    //deposit money
    public deposit(amount : number) : void {
        console.log("deposit from bank account");
        this._balance += amount;
    }
    //withdraw money
    public withdraw(amount : number) : void {
        this._balance -= amount;
    }
}

2) In the child class we are going to inherit from the previously created class like this

import { BankAccount } from './bank-account';

export class CheckingAccount extends BankAccount {

    constructor(accuntSettings : any) {
        super(accuntSettings);
        console.log("constructor CheckingAccount");
    }
}

3) in the main class we will create the object and pass the initial values as parameters

const _checkingAccount = new CheckingAccount({
    id: 1,
    title: 'Checking Account',
    balance: 100,
    accountType: AccountType.Checking
});

4) We call the deposit method of the parent class and we will see what the current balance is

```//Deposit 50 _checkingAccount.deposit(55);

//show balance console.log("Balance: ",_checkingAccount.balance);

5) run the project and check the console

![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1659719375515/2Lggq5QTf.png align="left")

6) we can override the method of the parent class in the child class, and add a different functionality

import { BankAccount } from './bank-account';

export class CheckingAccount extends BankAccount {

constructor(accuntSettings : any) {
    super(accuntSettings);
    console.log("constructor CheckingAccount");
}

deposit(amount : number) : void {
    console.log("deposit from checking account");
    this.balance += amount * 1.05;
}

} ```

7) run the project and check the console

image.png

Blue Nerd Gaming Sport and Esport Logo.png