📜  D编程-接口

📅  最后修改于: 2020-11-04 05:20:56             🧑  作者: Mango


接口是一种强制从其继承的类必须实现某些功能或变量的方式。不能在接口中实现函数,因为它们总是在从接口继承的类中实现。

尽管两者在很多方面都相似,但是使用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方法,其本身应包含对其的定义。这些函数不能被派生类覆盖。一个简单的例子如下所示。

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