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