官术网_书友最值得收藏!

Abstract classes

Abstract classes are a special type of class that can only be inherited from and not instantiated. They are declared with the abstract keyword, as in the following example:

  1. We can define a base Product class as follows:
abstract class Product {
name: string;
unitPrice: number;
}
  1. If we try to create an instance of this, the compiler will complain, as we would expect:

  1. We can create a more specific usable class for food products by extending Product:
class Food extends Product {
constructor(public bestBefore: Date) {
super();
}
}
  1. Here, we are adding a bestBefore date in our Food class. We can then create an instance of Food, passing in the bestBefore date:
const bread = new Food(new Date(2019, 6, 1));

Abstract classes can have abstract methods that child classes must implement. Abstract methods are declared with the abstract keyword in front of them, as in the following example:

  1. Let's add an abstract method to our base Product class:
abstract class Product {
name: string;
unitPrice: number;
abstract delete(): void;
}
  1. After we add the abstract method, the compiler immediately complains about our Food class because it doesn't implement the delete method:

  1. So, let's fix this and implement the delete method:
class Food extends Product {
deleted: boolean;

constructor(public bestBefore: Date) {
super();
}

delete() {
this.deleted = false;
}
}
主站蜘蛛池模板: 上饶县| 邹城市| 吉木乃县| 交口县| 滕州市| 克山县| 嘉善县| 太白县| 凤山县| 公安县| 冷水江市| 黄平县| 湘乡市| 濮阳市| 海盐县| 阜城县| 惠东县| 怀远县| 庄河市| 封丘县| 台北市| 朝阳区| 卓尼县| 扎鲁特旗| 简阳市| 建德市| 溧水县| 汪清县| 视频| 忻州市| 鹤岗市| 大英县| 合山市| 陇南市| 南召县| 五台县| 开封市| 赤壁市| 阿鲁科尔沁旗| 孟村| 长葛市|