接口是迫使从它继承的类必须实现某些功能或变量的方法。函数不能在一个接口来实现,因为它们在从接口继承的类总是执行。使用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
一个接口可以有最终的和静态方法的定义应包括在接口本身。这些功能不能过度由派生类重载。一个简单的例子如下所示。
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