MST

星途 面试题库

面试题:TypeScript 类继承中的抽象类与接口

在TypeScript 中,定义一个抽象类 `Shape`,它有抽象方法 `getArea`。然后定义 `Circle` 和 `Rectangle` 类继承自 `Shape` 并实现 `getArea` 方法。另外,定义一个接口 `Drawable`,有方法 `draw`,让 `Circle` 和 `Rectangle` 同时实现 `Drawable` 接口,并说明抽象类和接口在这种场景下各自的作用与区别。
28.2万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
// 定义抽象类 Shape
abstract class Shape {
    // 抽象方法 getArea
    abstract getArea(): number;
}

// 定义接口 Drawable
interface Drawable {
    draw(): void;
}

// 定义 Circle 类,继承自 Shape 并实现 Drawable 接口
class Circle extends Shape implements Drawable {
    constructor(private radius: number) {
        super();
    }
    // 实现 getArea 方法
    getArea(): number {
        return Math.PI * this.radius * this.radius;
    }
    // 实现 draw 方法
    draw(): void {
        console.log(`绘制一个半径为 ${this.radius} 的圆`);
    }
}

// 定义 Rectangle 类,继承自 Shape 并实现 Drawable 接口
class Rectangle extends Shape implements Drawable {
    constructor(private width: number, private height: number) {
        super();
    }
    // 实现 getArea 方法
    getArea(): number {
        return this.width * this.height;
    }
    // 实现 draw 方法
    draw(): void {
        console.log(`绘制一个宽为 ${this.width},高为 ${this.height} 的矩形`);
    }
}

抽象类和接口在这种场景下的作用

  • 抽象类Shape 抽象类为 CircleRectangle 提供了一个公共的基类,定义了它们都需要实现的 getArea 方法,强制子类去实现特定的行为,保证了继承体系中方法的一致性。同时,抽象类也可以包含一些成员变量和具体方法,为子类提供通用的属性和行为。
  • 接口Drawable 接口定义了 draw 方法,让 CircleRectangle 实现这个方法,使得这两个类具有了绘制的能力。接口的作用在于将不同类的行为进行统一抽象,只要实现了该接口,就表示具有某种特定的能力,它可以让不相关的类实现同一个接口,增加代码的灵活性和可扩展性。

抽象类和接口在这种场景下的区别

  • 定义方式:抽象类使用 abstract class 定义,接口使用 interface 定义。
  • 实现机制:一个类只能继承一个抽象类,但可以实现多个接口。
  • 成员内容:抽象类可以包含抽象方法和具体方法,也可以有成员变量;接口只能包含抽象方法(TypeScript 中可以有可选属性和只读属性等特殊情况),不能包含成员变量。
  • 应用场景:抽象类更适合用于存在公共逻辑和状态的情况,为子类提供一个通用的基础;接口更适合用于定义行为契约,使不相关的类具有相同的行为,实现多态和可插拔性。