JavaScript Editor JavaScript Editor     JavaScript Debugger

Previous Section Next Section

Main Page

Using Private Inheritance

If you make a class member private, it's available only in the present class—not outside that class, and not in any class derived from that class. For example, if I made the MainForm member of the Animal class private in the Inheritance example on the CD-ROM, as discussed in the previous topic and in the In Depth section of this chapter, then that member would not be available in the derived class named Dog. That means this code wouldn't work, because I've made MainForm private but tried to use it in the derived Dog class (note also that the button event handlers are private in the Form1 class, which means they can't be used in any class derived from Form1):

Public Class Form1
    Inherits System.Windows.Forms.Form

    'Windows Form Designer generated code

    Dim spot As Dog
    Dim jaws As Fish

    Private Sub Button1_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles Button1.Click
        spot = New Dog(Me)
        spot.Breathing()
    End Sub

    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
    Private 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 Dog
    Inherits Animal

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

    Public Sub Barking()
        MainForm.TextBox1.Text = "Barking..." 'Will not work now!!!
    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()
        MainForm.TextBox1.Text = "Bubbling..."
    End Sub
End Class

Note that if you declare a class Private, all the members in it are restricted to that class.

Previous Section Next Section




JavaScript Editor Free JavaScript Editor     JavaScript Editor