JavaScript Editor JavaScript Editor     JavaScript Debugger

Previous Section Next Section

Main Page

Overriding Base Class Members

As discussed in the In Depth section of this chapter, when you inherit from a base class, you can override (replace) base class members in the derived class. We saw how that worked in the In Depth section of this chapter with the Inheritance example from the CD-ROM with the Fish class, which overrode the Animal base class's Breathe method. The Animal class's Breathe method displayed "Breathing" but the Fish class's version displayed "Bubbling". I have to make the Animal class's version overridable with the Overridable keyword and indicate that the Fish class's version is overriding it by using the Overrides keyword:

Public Class Form1
    Inherits System.Windows.Forms.Form

    'Windows Form Designer generated code

    Dim jaws As Fish
        
    Private Sub Button2_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles Button2.Click
        jaws = New Fish(Me)
        jaws.Breathing()
    End Sub
End Class

Public Class Animal
    Protected MainForm As Form1
    Public Sub New(ByVal form1 As Form1)
        MainForm = form1
    End Sub

    Public Overridable Sub Breathing()
        MainForm.TextBox1.Text = "Breathing..."
    End Sub
End Class
        
Public Class Fish
    Inherits Animal

    Public Sub New(ByVal form1 As Form1)
        MyBase.New(form1)
    End Sub

    Public Overrides Sub Breathing()
        MyBase.MainForm.TextBox1.Text = "Bubbling..."
    End Sub
End Class

You can see the result in Figure 12.2, where the Fish class's Breathe method is displaying "Bubbling". Don't confuse overriding, which replaces a base class member, with overloading, which we saw in Chapter 11; overloading lets you use different argument lists with methods and properties.

Related solution:

Found on page:

Overloading Methods and Properties

513

Previous Section Next Section




JavaScript Editor Free JavaScript Editor     JavaScript Editor