- 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;
}
}
推薦閱讀
- 程序員修煉之道:程序設(shè)計入門30講
- Reactive Programming with Swift
- Learning ASP.NET Core 2.0
- Java程序員面試算法寶典
- VSTO開發(fā)入門教程
- Implementing Cisco Networking Solutions
- Building Mapping Applications with QGIS
- Hands-On Microservices with Kotlin
- C程序設(shè)計案例教程
- 從0到1:Python數(shù)據(jù)分析
- Mastering AWS Security
- Machine Learning for Developers
- Hands-On Robotics Programming with C++
- TypeScript圖形渲染實戰(zhàn):2D架構(gòu)設(shè)計與實現(xiàn)
- 基于MATLAB的控制系統(tǒng)仿真及應(yīng)用