目录

D编程 - 抽象类(Abstract Classes)

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

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

在D中使用抽象类

使用abstract关键字声明类抽象。 关键字出现在类关键字之前的类声明中。 以下显示了如何继承和使用抽象类的示例。

例子 (Example)

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

抽象函数 (Abstract Functions)

与函数类似,类也可以是抽象的。 这个函数的实现没有在它的类中给出,但应该在使用抽象函数继承类的类中提供。 上面的例子用抽象函数更新。

例子 (Example)

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 
↑回到顶部↑
WIKI教程 @2018