如果很多類都有通性,我們就定義一個抽象類
抽象類中即可以
- 定義抽象方法
- 可以定義具體的方法
- 定義屬性
abstract class Geom {
type:string
abstract getArea(): number;
getName() {
console.log("gemo");
}
}
抽象類必須用繼承去實現(xiàn),繼承的類稱為抽象類的實現(xiàn)類
定義兩個類:Square,Circle
每個類中有這個類具體的方法去實現(xiàn)抽象類中定義的抽象方法
abstract class Geom {
type: string;
abstract getArea(): number;
getName() {
console.log("gemo");
}
}
class Square extends Geom {
constructor(private side: number) {
super();
}
getArea() {
return this.side * this.side;
}
}
class Circle extends Geom {
constructor(private radius: number) {
super();
}
getArea() {
return 2 * 3.14 * this.radius;
}
}
const square = new Square(2);
const circle = new Circle(2);
//output
//4
//12.56
在實際開發(fā)中,抽象類會結(jié)合接口一起使用,遇到類似場景和設(shè)計模式會繼續(xù)更新。