How to call base class constructor from child class in TypeScript ?
Last Updated :
14 Jun, 2021
In this article, we will learn how we can call the base class constructor from the child class. When a class inherits the properties of another class, it is called a child class and the class whose properties are inherited is called the parent class and the whole process is called Inheritance. In Inheritance, the child class acquires the properties of the base class or parent class.
You can call the base class constructor from the child class by using the super() which will execute the constructor of the base class.
Example:
Javascript
class Person {
Name: string;
Profession: string;
constructor(name: string, profession: string) {
this .Name = name;
this .Profession = profession;
}
}
class Details extends Person {
Name: string;
Profession: string;
constructor(name: string, profession: string) {
super (name, profession);
this .Name = name;
this .Profession = profession;
}
details(): string {
return this .Name + " is " +
this .Profession;
}
}
var data =
new Details( "A" , "Android Developer" );
var data2 =
new Details( "B" , "Web Developer" );
console.log(data.details());
console.log(data2.details());
|
Output:
A is Android Developer
B is Web Developer
Here, the Person class is our parent class and the Details class is our child class and also the Details class inherits the Person class. For Inheriting another class extends keyword is used. The Details class inherits the properties of the Person class.
Now in the derived class, we have used the super() which will call the constructor of the base class or parent class. After this, we have created an instance of the Details class and passed two parameters name and profession to its constructor and after this, we have called the details method which will print the value provided into the constructor parameter.
Example 2:
Javascript
class Square {
side: number;
constructor(side: number) {
this .side = side;
}
}
class Area extends Square {
side: number;
constructor(side: number) {
super (side);
this .side = side;
}
area(): string {
return "The area of Square is " + t
his.side * this .side;
}
}
var data = new Area(7);
console.log(data.area());
|
Output:
The area of Square is 49
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...