无涯教程-D语言 - 抽象类

87 阅读2分钟

抽象是指在OOP中使类抽象的能力。抽象类是无法化的类。该类的所有其他函数仍然存在,并且以相同的方式访问其字段,方法和构造函数。您只是无法创建抽象类的。

如果一个类是抽象的并且无法化,则除非是子类,否则该类没有太多用处。这通常是抽象类在设计阶段出现的方式。父类包含子类集合的通用函数,但是父类本身太抽象,无法单独使用。

使用抽象类

使用 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="Learnfk";

writeln(emp.name); writeln(emp.getAge); }

当我们编译并运行上述程序时,我们将获得以下输出。

Learnfk
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="Learnfk"; emp.print(); }

当我们编译并运行上述程序时,我们将获得以下输出。

The employee details are as follows: 
Emp ID: 101 
Emp Name: Learnfk 
Age: 37 

参考链接

www.learnfk.com/d-programmi…