D语言 - 接口

D语言 - 接口 首页 / D语言入门教程 / D语言 - 接口

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

当您想从一个接口继承而该类已经从另一个类继承时,则需要用逗号分隔该类的名称和接口的名称。

链接: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 函数接口

接口可以具有finalstatic方法,其自身应包含对其的定义,这些函数不能被子类覆盖,一个简单的如下所示。

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

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

技术与商业案例解读 -〔徐飞〕

代码精进之路 -〔范学雷〕

研发效率破局之道 -〔葛俊〕

全栈工程师修炼指南 -〔熊燚(四火)〕

设计模式之美 -〔王争〕

Redis核心技术与实战 -〔蒋德钧〕

超级访谈:对话张雪峰 -〔张雪峰〕

中间件核心技术与实战 -〔丁威〕

Serverless进阶实战课 -〔静远〕

好记忆不如烂笔头。留下您的足迹吧 :)