
- D 程式設計基礎
- D 程式設計 - 首頁
- D 程式設計 - 概述
- D 程式設計 - 環境
- D 程式設計 - 基本語法
- D 程式設計 - 變數
- D 程式設計 - 資料型別
- D 程式設計 - 列舉
- D 程式設計 - 字面量
- D 程式設計 - 運算子
- D 程式設計 - 迴圈
- D 程式設計 - 條件語句
- D 程式設計 - 函式
- D 程式設計 - 字元
- D 程式設計 - 字串
- D 程式設計 - 陣列
- D 程式設計 - 關聯陣列
- D 程式設計 - 指標
- D 程式設計 - 元組
- D 程式設計 - 結構體
- D 程式設計 - 聯合體
- D 程式設計 - 範圍
- D 程式設計 - 別名
- D 程式設計 - Mixins
- D 程式設計 - 模組
- D 程式設計 - 模板
- D 程式設計 - 不可變物件
- D 程式設計 - 檔案 I/O
- D 程式設計 - 併發
- D 程式設計 - 異常處理
- D 程式設計 - 合約
- D - 條件編譯
- D 程式設計 - 面向物件
- D 程式設計 - 類與物件
- D 程式設計 - 繼承
- D 程式設計 - 過載
- D 程式設計 - 封裝
- D 程式設計 - 介面
- D 程式設計 - 抽象類
- D 程式設計 - 有用資源
- 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
D 語言中帶有 final 和 static 函式的介面
介面可以具有 final 和 static 方法,其定義應包含在介面本身中。這些函式不能被派生類覆蓋。下面顯示了一個簡單的示例。
示例
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
廣告