在TypeScript中实现继承非常简洁且直观,主要通过使用关键字extends
来实现。继承允许我们创建一个类(子类)来继承另一个类(父类)的属性和方法,同时还可以添加或重写方法和属性。这是面向对象编程中的一个核心概念,有助于代码的重用和组织。
示例
假设我们有一个基类叫做Vehicle
,它有一些基本的属性和方法,然后我们想创建一个Car
类,它继承Vehicle
类的属性和方法,同时增加一些特有的属性和方法。
typescript// 定义父类 class Vehicle { // 属性 public brand: string; public model: string; // 构造函数 constructor(brand: string, model: string) { this.brand = brand; this.model = model; } // 方法 displayInfo(): void { console.log(`This vehicle is a ${this.brand} ${this.model}`); } } // 定义子类 class Car extends Vehicle { // 新增属性 public doors: number; // 构造函数 constructor(brand: string, model: string, doors: number) { super(brand, model); // 调用父类的构造函数 this.doors = doors; } // 重写方法 displayInfo(): void { super.displayInfo(); // 调用父类的方法 console.log(`It has ${this.doors} doors.`); } } // 创建Car的实例 let myCar = new Car("Toyota", "Corolla", 4); myCar.displayInfo(); // 输出: This vehicle is a Toyota Corolla // It has 4 doors.
解释
-
类的定义:我们首先定义了一个
Vehicle
类,它拥有基本的属性如brand
和model
,以及一个显示信息的方法displayInfo()
。 -
继承:
Car
类通过使用extends
关键字继承了Vehicle
类。这意味着Car
类继承了所有来自Vehicle
类的属性和方法。 -
super关键字:在
Car
类的构造函数中,我们通过调用super()
来调用父类Vehicle
的构造函数,这是初始化继承自父类的属性的必要步骤。在displayInfo()
方法中,通过super.displayInfo()
调用父类的同名方法,然后添加额外的逻辑。 -
重写方法:在子类中,我们可以通过定义与父类同名的方法来对方法进行重写。在这个例子中,
Car
类重写了displayInfo()
方法。
这个例子展示了如何在TypeScript中使用继承来创建具有额外功能的新类,同时保持代码结构的简洁和可维护性。继承是实现代码复用和逻辑分层的重要手段之一。
2024年7月29日 13:54 回复