抽象是指能夠使一個(gè)抽象類在面向?qū)ο缶幊痰哪芰?。抽象類是不能被?shí)例化。該類別的所有其他功能仍然存在,及其字段、方法和構(gòu)造函數(shù)以相同的方式被訪問的。不能創(chuàng)建抽象類的實(shí)例。
如果一個(gè)類是抽象的,不能被實(shí)例化,類沒有多大用處,除非它是子類。這通常是在設(shè)計(jì)階段的抽象類是怎么來的。父類包含子類的集合的通用功能,但父類本身是過于抽象而被單獨(dú)使用。
使用abstract關(guān)鍵字來聲明一個(gè)類的抽象。關(guān)鍵字出現(xiàn)在類聲明的地方class關(guān)鍵字前。下面顯示了如何抽象類可以繼承和使用的例子。
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); }
當(dāng)我們編譯并運(yùn)行上面的程序,我們會(huì)得到下面的輸出。
Emp1 34
類似的函數(shù),類也可以做成抽象。這種功能的實(shí)現(xiàn)是不是在同級(jí)類中給出,但應(yīng)在繼承的類與抽象函數(shù)的類來提供。上述例子是用抽象的功能更新,并在下面給出。
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(); }
當(dāng)我們編譯并運(yùn)行上面的程序,我們會(huì)得到下面的輸出。
The employee details are as follows: Emp ID: 101 Emp Name: Emp1 Age: 34