接口是一種強(qiáng)制從其繼承的類(lèi)必須實(shí)現(xiàn)某些函數(shù)或變量的方式,不能在接口中實(shí)現(xiàn)函數(shù),因?yàn)樗枰诮涌诘睦^承類(lèi)中實(shí)現(xiàn)。
當(dāng)您想從一個(gè)接口繼承而該類(lèi)已經(jīng)從另一個(gè)類(lèi)繼承時(shí),則需要用逗號(hào)分隔該類(lèi)的名稱(chēng)和接口的名稱(chēng)。
讓我們看一個(gè)簡(jiǎn)單的示例,它說(shuō)明了接口的用法。
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());
}
編譯并執(zhí)行上述代碼后,將產(chǎn)生以下輸出-
Total area: 35
接口可以具有final和static方法,其自身應(yīng)包含對(duì)其的定義,這些函數(shù)不能被子類(lèi)覆蓋,一個(gè)簡(jiǎn)單的如下所示。
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();
}
編譯并執(zhí)行上述代碼后,將產(chǎn)生以下輸出-
Total area: 35
This is a static method
This is a final method
更多建議: