接口是一种强制从其继承的类必须实现某些函数或变量的方式,不能在接口中实现函数,因为它需要在接口的继承类中实现。
当您想从一个接口继承而该类已经从另一个类继承时,则需要用逗号分隔该类的名称和接口的名称。
链接:https://www.learnfk.comhttps://www.learnfk.com/d-programming/d-programming-interfaces.html
来源:LearnFk无涯教程网
让我们看一个简单的示例,它说明了接口的用法。
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("Learnfk Total area: ", Rect.getArea()); }
编译并执行上述代码后,将产生以下输出-
Learnfk Total area: 35
接口可以具有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("Learnfk Total area: ", rect.getArea()); rect.myfunction1(); rect.myfunction2(); }
编译并执行上述代码后,将产生以下输出-
Learnfk Total area: 35 This is a static method This is a final method
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)
Spring Cloud 微服务项目实战 -〔姚秋辰(姚半仙)〕