D 程式設計 - 抽象類



抽象指的是在面向物件程式設計中使類成為抽象類的能力。抽象類是不能被例項化的類。類的所有其他功能仍然存在,其欄位、方法和建構函式都以相同的方式訪問。你只是不能建立抽象類的例項。

如果一個類是抽象的並且不能被例項化,那麼除非它是子類,否則這個類就沒有多大用處。這通常是抽象類在設計階段出現的方式。父類包含一組子類的公共功能,但是父類本身過於抽象而無法獨立使用。

在 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
37

抽象函式

與函式類似,類也可以是抽象的。此類函式的實現並未在其類中給出,而應該在其繼承包含抽象函式的類的類中提供。以上示例已更新為包含抽象函式。

示例

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 
廣告
© . All rights reserved.