- Learn React with TypeScript 3
- Carl Rippon
- 224字
- 2021-06-10 19:16:35
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:
- We can define a base Product class as follows:
abstract class Product {
name: string;
unitPrice: number;
}
- If we try to create an instance of this, the compiler will complain, as we would expect:
- We can create a more specific usable class for food products by extending Product:
class Food extends Product {
constructor(public bestBefore: Date) {
super();
}
}
- 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:
- Let's add an abstract method to our base Product class:
abstract class Product {
name: string;
unitPrice: number;
abstract delete(): void;
}
- After we add the abstract method, the compiler immediately complains about our Food class because it doesn't implement the delete method:
- 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;
}
}
推薦閱讀
- 在最好的年紀學Python:小學生趣味編程
- Learn to Create WordPress Themes by Building 5 Projects
- Python從菜鳥到高手(第2版)
- SQL語言從入門到精通
- Instant QlikView 11 Application Development
- Magento 1.8 Development Cookbook
- Java EE 8 Application Development
- AppInventor實踐教程:Android智能應用開發前傳
- 現代C++編程實戰:132個核心技巧示例(原書第2版)
- HoloLens與混合現實開發
- 運維前線:一線運維專家的運維方法、技巧與實踐
- Lift Application Development Cookbook
- 從程序員角度學習數據庫技術(藍橋杯軟件大賽培訓教材-Java方向)
- OpenCV Android Programming By Example
- WebStorm Essentials