abstract class Shape {
// コンストラクタで共通のプロパティを定義
constructor(protected color: string) {}
// 具体的なメソッド(サブクラスでそのまま使える)
describe(): void {
console.log(`This is a ${this.color} shape.`);
}
// 抽象メソッド(サブクラスで実装必須)
abstract getArea(): number;
}
class Circle extends Shape {
constructor(color: string, private radius: number) {
super(color);
}
// 必須の抽象メソッドを実装
getArea(): number {
return Math.PI * this.radius ** 2;
}
}
class Rectangle extends Shape {
constructor(color: string, private width: number, private height: number) {
super(color);
}
getArea(): number {
return this.width * this.height;
}
}
// インスタンス作成
const circle = new Circle("red", 10);
console.log(circle.getArea()); // 314.159...
circle.describe(); // This is a red shape.
const rectangle = new Rectangle("blue", 5, 8);
console.log(rectangle.getArea()); // 40
rectangle.describe(); // This is a blue shape.