D 语言 - 抽象类
抽象是指在 OOP 中使类抽象的能力。 抽象类是无法实例化的类。 该类的所有其他功能仍然存在,并且其字段、方法和构造函数都以相同的方式访问。 您只是无法创建抽象类的实例。
如果一个类是抽象的并且无法实例化,那么该类没有多大用处,除非它是子类。 这通常是设计阶段抽象类的产生方式。 父类包含子类集合的通用功能,但父类本身过于抽象,无法单独使用。
在 D 中使用抽象类
使用 abstract 关键字来声明类抽象。 该关键字出现在类声明中类关键字之前的某个位置。 下面展示了如何继承和使用抽象类的示例。
示例
import std.stdio;
import std.string;
import std.datetime;
abstract class Person {
int birthYear, birthDay, birthMonth;
string name;
int getAge() {
SysTime sysTime = Clock.currTime();
return sysTime.year - birthYear;
}
}
class Employee : Person {
int empID;
}
void main() {
Employee emp = new Employee();
emp.empID = 101;
emp.birthYear = 1980;
emp.birthDay = 10;
emp.birthMonth = 10;
emp.name = "Emp1";
writeln(emp.name);
writeln(emp.getAge);
}
当我们编译并运行上面的程序时,我们将得到以下输出。
Emp1 37
抽象函数
与函数类似,类也可以是抽象的。 此类函数的实现不在其类中给出,而应在继承具有抽象函数的类的类中提供。 上面的例子用抽象函数进行了更新。
示例
import std.stdio;
import std.string;
import std.datetime;
abstract class Person {
int birthYear, birthDay, birthMonth;
string name;
int getAge() {
SysTime sysTime = Clock.currTime();
return sysTime.year - birthYear;
}
abstract void print();
}
class Employee : Person {
int empID;
override void print() {
writeln("The employee details are as follows:");
writeln("Emp ID: ", this.empID);
writeln("Emp Name: ", this.name);
writeln("Age: ",this.getAge);
}
}
void main() {
Employee emp = new Employee();
emp.empID = 101;
emp.birthYear = 1980;
emp.birthDay = 10;
emp.birthMonth = 10;
emp.name = "Emp1";
emp.print();
}
当我们编译并运行上面的程序时,我们将得到以下输出。
The employee details are as follows: Emp ID: 101 Emp Name: Emp1 Age: 37

