抽象是指能够使一个抽象类在面向对象编程的能力。抽象类是不能被实例化。该类别的所有其他功能仍然存在,及其字段、方法和构造函数以相同的方式被访问的。不能创建抽象类的实例。
如果一个类是抽象的,不能被实例化,类没有多大用处,除非它是子类。这通常是在设计阶段的抽象类是怎么来的。父类包含子类的集合的通用功能,但父类本身是过于抽象而被单独使用。
使用abstract关键字来声明一个类的抽象。关键字出现在类声明的地方class关键字前。下面显示了如何抽象类可以继承和使用的例子。
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 34抽象函数
类似的函数,类也可以做成抽象。这种功能的实现是不是在同级类中给出,但应在继承的类与抽象函数的类来提供。上述例子是用抽象的功能更新,并在下面给出。
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: 34