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

How can you achieve inheritance in TypeScript?

1个答案

1

In TypeScript, implementing inheritance offers a concise and intuitive approach, primarily achieved by using the extends keyword. Inheritance enables us to create a class (subclass) that inherits properties and methods from another class (superclass), while also adding or overriding methods and properties. This is a core concept in object-oriented programming, facilitating code reuse and organization.

Example

Assume we have a base class called Vehicle with basic properties and methods, and we want to create a Car class that inherits from Vehicle while introducing specific properties and methods.

typescript
// Define the superclass class Vehicle { // Properties public brand: string; public model: string; // Constructor constructor(brand: string, model: string) { this.brand = brand; this.model = model; } // Method displayInfo(): void { console.log(`This vehicle is a ${this.brand} ${this.model}`); } } // Define the subclass class Car extends Vehicle { // New property public doors: number; // Constructor constructor(brand: string, model: string, doors: number) { super(brand, model); // Call the superclass constructor this.doors = doors; } // Override method displayInfo(): void { super.displayInfo(); // Call the superclass method console.log(`It has ${this.doors} doors.`); } } // Create an instance of Car let myCar = new Car("Toyota", "Corolla", 4); myCar.displayInfo(); // Output: This vehicle is a Toyota Corolla // It has 4 doors.

Explanation

  1. Class Definition: We first define a Vehicle class with basic properties such as brand and model, and a method displayInfo().

  2. Inheritance: The Car class inherits from Vehicle using the extends keyword. This means the Car class inherits all properties and methods from the Vehicle class.

  3. super Keyword: In the Car class constructor, we call super() to invoke the Vehicle class constructor, which is necessary for initializing inherited properties. Within the displayInfo() method, we call super.displayInfo() to invoke the superclass method and then add additional logic.

  4. Overriding Methods: In the subclass, we can override methods by defining methods with the same name as in the superclass. In this example, the Car class overrides the displayInfo() method.

This example demonstrates how to use inheritance in TypeScript to create new classes with additional functionality while maintaining concise and maintainable code structure. Inheritance is a key mechanism for achieving code reuse and logical layering.

2024年7月29日 13:54 回复

你的答案