接口是迫使從它繼承的類必須實現(xiàn)某些功能或變量的方法。函數(shù)不能在一個接口來實現(xiàn),因為它們在從接口繼承的類總是執(zhí)行。使用interface關鍵字代替,盡管兩者在很多方面是相似的class關鍵字創(chuàng)建一個接口。當你想從一個接口繼承和類已經(jīng)從另一個類繼承,那么需要單獨的類的名稱,并用逗號將接口的名稱。
讓我們來看一個簡單的例子,說明使用的接口。
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()); }
當上面的代碼被編譯并執(zhí)行,它會產(chǎn)生以下結果:
Total area: 35
一個接口可以有最終的和靜態(tài)方法的定義應包括在接口本身。這些功能不能過度由派生類重載。一個簡單的例子如下所示。
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(); }
讓我們編譯和運行上面的程序,這將產(chǎn)生以下結果:
Total area: 35 This is a static method This is a final method