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