示例工程 07-classes-interfaces

07-classes-interfaces/02-abstract/src/main.ts

typescript · 0.9 KB

运行:07 · abstract

点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。

// 演示:抽象类约束子类必须实现抽象成员,同时共享具体方法
export abstract class Shape {
  abstract area(): number;
 
  protected abstract get kind(): string;
 
  describe(): string {
    return `${this.kind}:${this.area().toFixed(2)}`;
  }
}
 
export class Circle extends Shape {
  constructor(private readonly radius: number) {
    super();
  }
 
  protected get kind(): string {
    return 'circle';
  }
 
  area(): number {
    return Math.PI * this.radius ** 2;
  }
}
 
export class Square extends Shape {
  constructor(private readonly side: number) {
    super();
  }
 
  protected get kind(): string {
    return 'square';
  }
 
  area(): number {
    return this.side ** 2;
  }
}
 
export function run(log: (msg: string) => void = console.log): string[] {
  const shapes: Shape[] = [new Circle(1), new Square(3)];
  const lines = shapes.map((shape) => shape.describe());
  for (const line of lines) {
    log(line);
  }
  return lines;
}