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

D 語言中帶有 final 和 static 函式的介面

介面可以具有 final 和 static 方法,其定義應包含在介面本身中。這些函式不能被派生類覆蓋。下面顯示了一個簡單的示例。

示例

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
廣告