簡單的介面 - 可飛行
介面 Flyable 是一個類模組,程式碼如下:
Public Sub Fly()
' No code.
End Sub
Public Function GetAltitude() As Long
' No code.
End Function
類模組 Airplane 使用 Implements 關鍵字告訴編譯器引發錯誤,除非它有兩個方法:Flyable_Fly() sub 和 Flyable_GetAltitude() 函式返回 Long。
Implements Flyable
Public Sub Flyable_Fly()
Debug.Print "Flying With Jet Engines!"
End Sub
Public Function Flyable_GetAltitude() As Long
Flyable_GetAltitude = 10000
End Function
第二類模組 Duck 也實現了 Flyable:
Implements Flyable
Public Sub Flyable_Fly()
Debug.Print "Flying With Wings!"
End Sub
Public Function Flyable_GetAltitude() As Long
Flyable_GetAltitude = 30
End Function
我們可以寫一個接受任何 Flyable 值的例程,知道它會響應 Fly 或 GetAltitude 的命令:
Public Sub FlyAndCheckAltitude(F As Flyable)
F.Fly
Debug.Print F.GetAltitude
End Sub
由於介面已定義,因此智慧感知彈出視窗將顯示 Fly 的 Fly 和 GetAltitude。
當我們執行以下程式碼時:
Dim MyDuck As New Duck
Dim MyAirplane As New Airplane
FlyAndCheckAltitude MyDuck
FlyAndCheckAltitude MyAirplane
輸出是:
Flying With Wings!
30
Flying With Jet Engines!
10000
請注意,即使子程式在 Airplane 和 Duck 中都被命名為 Flyable_Fly,當變數或引數定義為 Flyable 時,它也可以稱為 Fly。如果變數專門定義為 Duck,則必須將其稱為 Flyable_Fly。