Typescript学习笔记(9) ----- 抽象类

如果很多类都有通性,我们就定义一个抽象类
抽象类中即可以

  • 定义抽象方法
  • 可以定义具体的方法
  • 定义属性
abstract class Geom {
  type:string
  abstract getArea(): number;
  getName() {
    console.log("gemo");
  }
}

抽象类必须用继承去实现,继承的类称为抽象类的实现类
定义两个类:Square,Circle
每个类中有这个类具体的方法去实现抽象类中定义的抽象方法

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

在实际开发中,抽象类会结合接口一起使用,遇到类似场景和设计模式会继续更新。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容