VBA Interfaces Simple Interface - Flyable


Example

The interface Flyable is a class module with the following code:

Public Sub Fly()
    ' No code.
End Sub

Public Function GetAltitude() As Long
    ' No code.
End Function

A class module, Airplane, uses the Implements keyword to tell the compiler to raise an error unless it has two methods: a Flyable_Fly() sub and a Flyable_GetAltitude() function that returns a 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

A second class module, Duck, also implements 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

We can write a routine that accepts any Flyable value, knowing that it will respond to a command of Fly or GetAltitude:

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

Because the interface is defined, the IntelliSense popup window will show Fly and GetAltitude for F.

When we run the following code:

Dim MyDuck As New Duck
Dim MyAirplane As New Airplane

FlyAndCheckAltitude MyDuck
FlyAndCheckAltitude MyAirplane 

The output is:

Flying With Wings!
30
Flying With Jet Engines!
10000

Note that even though the subroutine is named Flyable_Fly in both Airplane and Duck, it can be called as Fly when the variable or parameter is defined as Flyable. If the variable is defined specifically as a Duck, it would have to be called as Flyable_Fly.