MST

星途 面试题库

面试题:TypeScript中抽象类的基础应用

请使用TypeScript创建一个抽象类`Shape`,包含抽象方法`getArea`,然后创建`Circle`和`Rectangle`类继承自`Shape`,并实现`getArea`方法。Circle类需要接收半径作为参数,Rectangle类需要接收长和宽作为参数。
45.5万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
abstract class Shape {
    abstract getArea(): number;
}

class Circle extends Shape {
    private radius: number;
    constructor(radius: number) {
        super();
        this.radius = radius;
    }
    getArea(): number {
        return Math.PI * this.radius * this.radius;
    }
}

class Rectangle extends Shape {
    private length: number;
    private width: number;
    constructor(length: number, width: number) {
        super();
        this.length = length;
        this.width = width;
    }
    getArea(): number {
        return this.length * this.width;
    }
}