Interfaces provide another way you can accomplish polymorphism in Visual Basic. Interfaces describe properties and methods like classes, but unlike classes, interfaces cannot provide any implementation. Multiple interfaces have the advantage of allowing systems of software components to evolve without breaking existing code.
To achieve polymorphism with interfaces, you implement an interface in different ways in several classes. Client applications can use either the old or the new implementations in exactly the same way. The advantage to interface-based polymorphism is that you do not need to re-compile existing client applications to get them to work with new interface implementations.
The following example defines an interface named Shape2 that is implemented in a class named RightTriangleClass2 and RectangleClass2. A procedure named ProcessShape2 calls the CalculateArea method of instances of RightTriangleClass2 or RectangleClass2:
Sub TestInterface() Dim RectangleObject2 As New RectangleClass2 Dim RightTriangleObject2 As New RightTriangleClass2 ProcessShape2(RightTriangleObject2, 3, 14) ProcessShape2(RectangleObject2, 3, 5) End Sub Sub ProcessShape2(ByVal Shape2 As Shape2, ByVal X As Double, _ ByVal Y As Double) MsgBox("The area of the object is " _ & Shape2.CalculateArea(X, Y)) End Sub Public Interface Shape2 Function CalculateArea(ByVal X As Double, ByVal Y As Double) As Double End Interface Public Class RightTriangleClass2 Implements Shape2 Function CalculateArea(ByVal X As Double, _ ByVal Y As Double) As Double Implements Shape2.CalculateArea ' Calculate the area of a right triangle. Return 0.5 * (X * Y) End Function End Class Public Class RectangleClass2 Implements Shape2 Function CalculateArea(ByVal X As Double, _ ByVal Y As Double) As Double Implements Shape2.CalculateArea ' Calculate the area of a rectangle. Return X * Y End Function End Class