×
D语言教程D语言概述,D语言是什么?D语言开发环境设置D语言基本语法D语言变量D语言数据类型D语言枚举EnumsD语言常值D语言运算符D中算术运算符D语言关系运算符D语言逻辑运算符D语言位运算符D语言赋值运算符D语言sizeof运算符D语言运算符优先级D语言循环D语言while循环D语言for循环D语言do...while循环D语言嵌套循环D语言break语句D语言continue语句D语言决策语句D语言if语句D语言if...else语句D语言if嵌套语句D语言switch语句D语言嵌套switch语句D语言函数D语言字符D语言字符串-StringD语言数组D语言关联数组D语言指针D语言元组D语言结构体D语言联合体D语言范围D语言别名D语言混合类型D语言模块D语言模板D语言常量D语言文件I/OD语言并发D语言异常处理契约式编程D语言条件编译D语言类和对象D语言类成员函数类的访问修饰符构造函数和析构函数this指针类指针类的静态成员类继承重载一元运算符重载二元运算符重载比较操作符重载D语言封装D语言接口D语言抽象类

D语言接口


接口是迫使从它继承的类必须实现某些功能或变量的方法。函数不能在一个接口来实现,因为它们在从接口继承的类总是执行。使用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

Final和静态函数接口

一个接口可以有最终的和静态方法的定义应包括在接口本身。这些功能不能过度由派生类重载。一个简单的例子如下所示。

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

分类导航

关注微信下载离线手册

bootwiki移动版 bootwiki
(群号:472910771)