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 { // Properties of the Person class Name: string; Profession: string; // Constructor of Person class constructor(name: string, profession: string) { this .Name = name; this .Profession = profession; } } class Details extends Person { // Properties of the class Name: string; Profession: string; // Constructor of the Details class constructor(name: string, profession: string) { // Calling the base class constructor super (name, profession); // Setting the properties this .Name = name; this .Profession = profession; } details(): string { return this .Name + " is " + this .Profession; } } // Creating an object var data = new Details( "A" , "Android Developer" ); var data2 = new Details( "B" , "Web Developer" ); // Accessing the function details() // and printing 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 { // Properties of the Square class side: number; // Constructor of the Square class constructor(side: number) { this .side = side; } } class Area extends Square { // Properties of the Area class side: number; // Constructor of the Area class constructor(side: number) { // Calling the base class constructor super (side); // Setting the properties this .side = side; } // Returns the area of square area(): string { return "The area of Square is " + t his.side * this .side; } } // Creating object of class Area var data = new Area(7); // Getting the property and // printing the value console.log(data.area()); |
Output:
The area of Square is 49