发布于 2015-08-16 14:43:12 | 231 次阅读 | 评论: 0 | 来源: 网络整理

接口是迫使从它继承的类必须实现某些功能或变量的方法。函数不能在一个接口来实现,因为它们在从接口继承的类总是执行。使用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
最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务