D语言抽象类

抽象是指能够使一个抽象类在面向对象编程的能力。抽象类是不能被实例化。该类别的所有其他功能仍然存在,及其字段、方法和构造函数以相同的方式被访问的。不能创建抽象类的实例。

如果一个类是抽象的,不能被实例化,类没有多大用处,除非它是子类。这通常是在设计阶段的抽象类是怎么来的。父类包含子类的集合的通用功能,但父类本身是过于抽象而被单独使用。

抽象类

使用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
联系我们

邮箱 626512443@qq.com
电话 18611320371(微信)
QQ群 235681453

Copyright © 2015-2022

备案号:京ICP备15003423号-3