如何在TypeScript中实现继承?


  在面向对象编程中,继承是一种基本的机制,它允许我们创建一个新类(子类)来继承另一个类(父类)的属性和方法。TypeScript支持类继承,并且提供了一套丰富的语法来实现这一功能。

1. 类继承

  在TypeScript中,我们使用extends关键字来实现类的继承。子类可以访问父类的公共和受保护成员,但不能访问私有成员。

// 父类
class Animal {
  private name: string;

  constructor(name: string) {
    this.name = name;
  }

  public speak(): void {
    console.log(`My name is ${this.name} and I can speak.`);
  }
}

// 子类
class Dog extends Animal {
  public speak(): void {
    console.log(`Woof! My name is ${this.name} and I can speak.`);
  }
}

// 使用子类
const dog = new Dog('Rex');
dog.speak(); // 输出: Woof! My name is Rex and I can speak.

  在这个例子中,我们定义了一个Animal类和一个从Animal继承的Dog类。Dog类重写了speak方法,以提供自己的实现。

2. 访问父类的构造函数

  在子类中,我们可以使用super关键字来访问父类的构造函数。这对于在子类的构造函数中初始化继承的属性非常有用。

class Person {
  private name: string;

  constructor(name: string) {
    this.name = name;
  }
}

class Employee extends Person {
  private department: string;

  constructor(name: string, department: string) {
    super(name);
    this.department = department;
  }

  public introduce(): void {
    console.log(`Hello, my name is ${this.name} and I work in ${this.department}.`);
  }
}

const employee = new Employee('Alice', 'Engineering');
employee.introduce(); // 输出: Hello, my name is Alice and I work in Engineering.

  在这个例子中,Employee类继承了Person类,并在其构造函数中调用了父类的构造函数来初始化name属性。同时,Employee类还添加了一个新的属性department。

3. 重写方法

  子类可以重写父类的方法,以提供自己的实现。这在实现多态行为时非常有用。

class Vehicle {
  public move(): void {
    console.log('The vehicle moves.');
  }
}

class Car extends Vehicle {
  public move(): void {
    console.log('The car moves.');
  }
}

const vehicle = new Vehicle();
const car = new Car();

vehicle.move(); // 输出: The vehicle moves.
car.move(); // 输出: The car moves.

  在这个例子中,Car类重写了Vehicle类的move方法,以提供特定的行为。

4. 访问父类的成员

  子类可以访问父类的公共和受保护成员,但不能访问私有成员。

class Base {
  public baseMethod(): void {
    console.log('This is a public method in Base.');
  }

  protected baseProtectedMethod(): void {
    console.log('This is a protected method in Base.');
  }

  // private basePrivateMethod(): void {
  //   console.log('This is a private method in Base.');
  // }
}

class Derived extends Base {
  public derivedMethod(): void {
    this.baseMethod(); // 允许
    this.baseProtectedMethod(); // 允许
    // this.basePrivateMethod(); // 不允许,会报错
  }
}

const derived = new Derived();
derived.derivedMethod(); // 输出: This is a public method in Base.

  在这个例子中,Derived类可以访问Base类的公共方法baseMethod和受保护方法baseProtectedMethod,但不能访问私有方法basePrivateMethod。

  • 8
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小新-alive

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值