D語言接口

接口是迫使從它繼承的類必須實現某些功能或變量的方法。函數不能在一個接口來實現,因爲它們在從接口繼承的類總是執行。使用interface關鍵字代替,儘管兩者在很多方面是相似的class關鍵字創建一個接口。當你想從一個接口繼承和類已經從另一個類繼承,那麼需要單獨的類的名稱,並用逗號將接口的名稱。

讓我們來看一個簡單的例子,說明使用的接口。

import std.stdio; // Base class interface Shape { public: void setWidth(int w); void setHeight(int h); } // Derived class class Rectangle: Shape { int width; int height; public: void setWidth(int w) { width = w; } void setHeight(int h) { height = h; } int getArea() { return (width * height); } } void main() { Rectangle Rect = new Rectangle(); Rect.setWidth(5); Rect.setHeight(7); // Print the area of the object. writeln("Total area: ", Rect.getArea()); }

當上面的代碼被編譯並執行,它會產生以下結果:

Total area: 35

Final和靜態函數接口

一個接口可以有最終的和靜態方法的定義應包括在接口本身。這些功能不能過度由派生類重載。一個簡單的例子如下所示。

import std.stdio; // Base class interface Shape { public: void setWidth(int w); void setHeight(int h); static void myfunction1() { writeln("This is a static method"); } final void myfunction2() { writeln("This is a final method"); } } // Derived class class Rectangle: Shape { int width; int height; public: void setWidth(int w) { width = w; } void setHeight(int h) { height = h; } int getArea() { return (width * height); } } void main() { Rectangle rect = new Rectangle(); rect.setWidth(5); rect.setHeight(7); // Print the area of the object. writeln("Total area: ", rect.getArea()); rect.myfunction1(); rect.myfunction2(); }

讓我們編譯和運行上面的程序,這將產生以下結果:

Total area: 35
This is a static method
This is a final method