D 语言 - 接口
接口是一种强制从它继承的类必须实现某些函数或变量的方法。 函数不得在接口中实现,因为它们始终在从接口继承的类中实现。
接口是使用interface关键字而不是class关键字创建的,尽管两者在很多方面都很相似。 当你想从一个接口继承并且该类已经从另一个类继承时,你需要用逗号分隔类的名称和接口的名称。
让我们看一个简单的例子来解释接口的使用。
示例
import std.stdio;
// 基类
interface Shape {
public:
void setWidth(int w);
void setHeight(int h);
}
// 派生类
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);
// 打印对象的面积。
writeln("Total area: ", Rect.getArea());
}
当上面的代码被编译并执行时,会产生以下结果 −
Total area: 35
与 D 中的Final和Static函数接口
接口可以具有Final方法和Static方法,其定义应包含在接口本身中。 这些函数不能被派生类重写。 下面显示了一个简单的示例。
示例
import std.stdio;
// 基类
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");
}
}
// 派生类
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);
// 打印对象的面积。
writeln("Total area: ", rect.getArea());
rect.myfunction1();
rect.myfunction2();
}
当上面的代码被编译并执行时,会产生以下结果 −
Total area: 35 This is a static method This is a final method

