目录

D Programming - Interfaces

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

使用interface关键字而不是class关键字创建interface ,即使两者在很多方面相似。 如果要从接口继承并且该类已从其他类继承,则需要使用逗号分隔类的名称和接口的名称。

让我们看一个解释接口使用的简单示例。

例子 (Example)

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方法,其定义应包含在接口本身中。 派生类不能覆盖这些函数。 一个简单的例子如下所示。

例子 (Example)

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
↑回到顶部↑
WIKI教程 @2018