D編程 抽象類

2021-09-01 10:52 更新

抽象是指在OOP中使類抽象的能力。抽象類是無法化的類。該類的所有其他函數(shù)仍然存在,并且以相同的方式訪問其字段,方法和構(gòu)造函數(shù)。您只是無法創(chuàng)建抽象類的。

如果一個類是抽象的并且無法化,則除非是子類,否則該類沒有太多用處。這通常是抽象類在設(shè)計階段出現(xiàn)的方式。父類包含子類集合的通用函數(shù),但是父類本身太抽象,無法單獨使用。

使用抽象類

使用 abstract 關(guān)鍵字聲明一個類摘要。關(guān)鍵字出現(xiàn)在類聲明中類關(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)我們編譯并運行上述程序時,我們將獲得以下輸出。

Emp1
37

抽象函數(shù)

與函數(shù)相似,類也可以是抽象的。此類函數(shù)的實現(xiàn)未在其類中給出,而應(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)我們編譯并運行上述程序時,我們將獲得以下輸出。

The employee details are as follows: 
Emp ID: 101 
Emp Name: Emp1 
Age: 37 


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號