user10601209
user10601209

Reputation:

How to override a constructor?

In my code I want to create a class called programmer which extends from the employee class.

The employee class constructor should take 4 parameters, and the programmer class constructor should take 5 parameters, 4 from the employee class and the other one from programmer class.

How can I do this?

class employee {

     private id: string;
     private name: string;
     private department: string;
     private salary: number;

    constructor(id: string , name: string , department: string , salary: number) {

        this.id = id;
        this.name = name;
        this.department = department;
        this.salary = salary;

    }



    speak() {
        console.log(`ID = ${this.id} , Name = ${this.name} , Department = ${this.department} , Salary = ${this.salary}`);
    }
}

class programmer extends employee {

    private programmingLang: string;

    constructor() {
        super();
    }

    speak() {
        super.speak() , console.log(` , Programming Language = ${this.programmingLang}`);
    }
}

Upvotes: 0

Views: 67

Answers (1)

Abdirahman
Abdirahman

Reputation: 180

i think your child class constructor should look like this.

Constructor(id: string , name: string , department: string , salary: 
number,programmingLang: string) {
super(id,name,department,salary);
this.programmingLang = programmingLang;
}

child class has all the properties of it's parent and also has it's specific properties such that child class constructor must take all these properties as parameter and call parent class constructor with those properties it inherts as argument and also initialize it's specific properties using this keyword.

I am not java script programmer but this is how inheritence works generaly in all OOP supported languages. Hope it helps.

Upvotes: 1

Related Questions