一類中的多個介面 - 可飛行和可擴充套件

使用 Flyable 示例作為起點,我們可以使用以下程式碼新增第二個介面 Swimmable

Sub Swim()
    ' No code
End Sub

Duck 物件可以飛行和游泳:

Implements Flyable
Implements Swimmable

Public Sub Flyable_Fly()
    Debug.Print "Flying With Wings!"
End Sub

Public Function Flyable_GetAltitude() As Long
    Flyable_GetAltitude = 30
End Function

Public Sub Swimmable_Swim()
    Debug.Print "Floating on the water"
End Sub

Fish 類也可以實現 Swimmable

Implements Swimmable

Public Sub Swimmable_Swim()
    Debug.Print "Swimming under the water"
End Sub

現在,我們可以看到 Duck 物件一方面可以作為 Flyable 傳遞給 Sub,另一方面可以傳遞給 Swimmable

Sub InterfaceTest()

Dim MyDuck As New Duck
Dim MyAirplane As New Airplane
Dim MyFish As New Fish

Debug.Print "Fly Check..."

FlyAndCheckAltitude MyDuck
FlyAndCheckAltitude MyAirplane

Debug.Print "Swim Check..."

TrySwimming MyDuck
TrySwimming MyFish

End Sub

Public Sub FlyAndCheckAltitude(F As Flyable)
    F.Fly
    Debug.Print F.GetAltitude
End Sub

Public Sub TrySwimming(S As Swimmable)
    S.Swim
End Sub

此程式碼的輸出是:

飛檢…

飛翔的翅膀!

三十

乘坐噴氣式飛機飛行!

10000

游泳檢查……

漂浮在水面上

在水下游泳