乐闻世界logo
搜索文章和话题

How the inheritance can be used in TypeScript?

1个答案

1

Steps to Use Inheritance:

  1. Define the base class (parent class): Start by defining a basic class that provides fundamental methods and properties, which other classes can inherit.

  2. Define the derived class (child class): Create a new class using the extends keyword to inherit the properties and methods of the base class.

  3. Override methods (optional): In the child class, you can override methods inherited from the parent class to provide more specific functionality.

  4. Use super to call parent class constructors and methods (optional): Within the child class constructor, use super() to invoke the parent class constructor. Additionally, you can call parent class methods from child class methods using the super keyword.

Example Code:

Assume we have a base class Vehicle with basic properties such as brand and methods like displayInfo():

typescript
class 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():

typescript
class 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:

typescript
let 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.

2024年7月29日 13:33 回复

你的答案