// 定义一个接口
interface Shape {
calculateArea(): number; // 定义了一个返回数字的方法
}
// 创建一个实现接口的类
class Circle implements Shape {
radius: number; // 圆的半径
// 构造函数接受半径作为参数
constructor(radius: number) {
this.radius = radius;
}
// 实现接口中的方法,计算圆的面积
calculateArea(): number {
return Math.PI * this.radius ** 2; // 使用数学公式计算面积
}
}
class Rectangle implements Shape {
width: number; // 矩形的宽度
height: number; // 矩形的高度
// 构造函数接受宽度和高度作为参数
constructor(width: number, height: number) {
this.width = width;
this.height = height;
}
// 实现接口中的方法,计算矩形的面积
calculateArea(): number {
return this.width * this.height; // 直接相乘得到面积
}
}
// 使用接口的函数
function printArea(shape: Shape) {
console.log(`The area is: ${shape.calculateArea()}`); // 打印出面积
}
// 创建一个半径为5的圆和一个宽度为3、高度为4的矩形
const myCircle = new Circle(5);
const myRectangle = new Rectangle(3, 4);
// 调用函数,打印出面积
printArea(myCircle); // 输出: "The area is: ~78.54"
printArea(myRectangle); // 输出: "The area is: 12"
TS语法Class类实现代码示例
最新推荐文章于 2025-05-20 11:57:34 发布