JavaScript Editor JavaScript Editor     JavaScript Debugger

Previous Section Next Section

Main Page

Inheritance-based Polymorphism

As discussed in the In Depth section of this chapter, polymorphism is a process that lets you store objects of a derived class in variables of a base class. You cannot, however, access any members not in the base class using the derived class variable. (The exception is that if the derived class overrides a base class method or property, the overriding method or property will be used.) The usual way to implement polymorphism is with inheritance. You can see this illustrated in the Polymorphism example on the CD-ROM, as covered in the In Depth section of this chapter. In that example, I create a class named Animal and derive a class, Fish, from it:

Public Class Animal
    Overridable Sub Breathe()
        MsgBox("Breathing...")
    End Sub
End Class

Public Class Fish
    Inherits Animal
    Overrides Sub Breathe()
        MsgBox("Bubbling...")
    End Sub
End Class

I also create a method named Display that you pass an object of the Animal class to:

    Public Sub Display(ByVal AnimalObject As Animal)
        AnimalObject.Breathe()
    End Sub

Because of polymorphism, we saw that you can pass objects of either Animal or Fish to the Display method:

Public Class Form1
    Inherits System.Windows.Forms.Form

    'Windows Form Designer generated code

    Private Sub Button1_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles Button1.Click
        Dim pet1 As New Animal()
        Dim pet2 As New Fish()
        Display(pet1)
        Display(pet2)
    End Sub

    Public Sub Display(ByVal AnimalObject As Animal)
        AnimalObject.Breathe()
    End Sub
End Class

You can see this program at work in Figure 12.5; for more details, see the In Depth section of this chapter.

Previous Section Next Section




JavaScript Editor Free JavaScript Editor     JavaScript Editor