Steps to Use Inheritance:
-
Define the base class (parent class): Start by defining a basic class that provides fundamental methods and properties, which other classes can inherit.
-
Define the derived class (child class): Create a new class using the
extendskeyword to inherit the properties and methods of the base class. -
Override methods (optional): In the child class, you can override methods inherited from the parent class to provide more specific functionality.
-
Use
superto call parent class constructors and methods (optional): Within the child class constructor, usesuper()to invoke the parent class constructor. Additionally, you can call parent class methods from child class methods using thesuperkeyword.
Example Code:
Assume we have a base class Vehicle with basic properties such as brand and methods like displayInfo():
typescriptclass Vehicle { brand: string; constructor(brand: string) { this.brand = brand; } displayInfo(): void { console.log(`This vehicle is made by ${this.brand}.`); } }
Now, we create a child class named Car that inherits from the Vehicle class, adding a new property model and a new method displayDetailedInfo():
typescriptclass Car extends Vehicle { model: string; constructor(brand: string, model: string) { super(brand); // Call the parent class constructor this.model = model; } displayDetailedInfo(): void { console.log(`This car is a ${this.brand} ${this.model}.`); } // Override the parent class method displayInfo(): void { super.displayInfo(); // Call the parent class displayInfo() console.log(`It is specifically a ${this.model}.`); } }
Usage Example:
typescriptlet myCar = new Car("Toyota", "Corolla"); myCar.displayInfo(); // Output: This vehicle is made by Toyota. It is specifically a Corolla. myCar.displayDetailedInfo(); // Output: This car is a Toyota Corolla.
This example demonstrates how to use inheritance, method overriding, and the super keyword to call parent class methods and constructors. These features make TypeScript very useful and easy to manage when dealing with complex object hierarchies.