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

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;
}
}
主站蜘蛛池模板: 柏乡县| 雅安市| 信丰县| 宁德市| 米易县| 河北区| 苍山县| 海丰县| 玉树县| 会宁县| 辽阳市| 东兰县| 苏尼特左旗| 思南县| 波密县| 镇沅| 石柱| 全州县| 永泰县| 乌拉特后旗| 长汀县| 皋兰县| 敦化市| 隆安县| 德阳市| 葫芦岛市| 弥渡县| 松溪县| 安溪县| 和林格尔县| 佛坪县| 厦门市| 博爱县| 左权县| 县级市| 宁国市| 县级市| 凭祥市| 佛坪县| 安顺市| 包头市|