As also discussed in the In Depth section of this chapter, interfaces provide another way you can support polymorphism in Visual Basic .NET. To implement polymorphism with interfaces, you create an interface and implement it in a number of other classes. You can then invoke the implemented method of the various objects you create in the same way. Here's how that works in the Polymorphism example on the CD-ROM; in this case, I create an interface named AnimalInterface with one method, Breathe, and implement that method in classes named Animal2 and Fish2:
Public Class Form1 Inherits System.Windows.Forms.Form 'Windows Form Designer generated code Private Sub Button2_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button2.Click Dim pet1 As New Animal2() Dim pet2 As New Fish2() Display2(pet1) Display2(pet2) End Sub Public Sub Display2(ByVal AnimalObject As AnimalInterface) AnimalObject.Breathe() End Sub End Class Public Interface AnimalInterface Sub Breathe() End Interface Public Class Animal2 Implements AnimalInterface Sub Breathe() Implements AnimalInterface.Breathe MsgBox("Breathing...") End Sub End Class Public Class Fish2 Implements AnimalInterface Sub Breathe() Implements AnimalInterface.Breathe MsgBox("Bubbling...") End Sub End Class
For more details, see the In Depth section of this chapter.