A Quick Inheritance Example

Create a new VB .NET Windows Application project and name it InheritanceTest. Add a button to the form and go to the code window. In the code, add the following class. Make sure that you add it outside the class for the form!

Public Class Person

   Dim msName, msAddress As String

   Property Name() As String
      Get
         Name = msName
      End Get
      Set(ByVal Value As String)
         msName = Value
      End Set
   End Property

   Property Address() As String
      Get
         Address = msAddress
      End Get
      Set(ByVal Value As String)
         msAddress = Value
      End Set
   End Property

   Public Function Enroll() As Boolean
      'check class enrollment
      'if enrollment < max. class size then
      'enroll person in class
      Enroll = True
   End Function
End Class

This code creates a Person class with two properties, Name and Address, and an Enroll method. So far, there is nothing about this class that you haven't seen before.

Now, add a second class, called Student. Your code should look like this:

Public Class Student
    Inherits Person
End Class

As you can see, there isn't any implementation code in Student at all. There are no properties or methods defined. Instead, all you do is inherit from Person.

Now, in the Button1_Click event handler on the form, add the following code:

Private Sub Button1_Click(ByVal sender As System.Object, _
 ByVal e As System.EventArgs) Handles Button1.Click
   Dim myStudent As New Student()
   MsgBox(myStudent.Enroll)
End Sub

Your form is creating an instance of the Student class. The only code in the Student class is an Inherits statement that inherits the Person class. However, because VB .NET supports implementation inheritance, you'll be able to call the Enroll method of the Person class from within the Student class, even though the Person class does not explicitly define an Enroll method. Instead, the Enroll method is present because Student is inheriting the method from Person. Go ahead and run the project to verify that the message box does report back a value of True.

Is it possible to instantiate Person directly? In this case, yes. For example, you could modify the Button1_Click event handler to look like this:

Dim myStudent As New Student()
Dim myPerson As New Person()
MsgBox(myStudent.Enroll)
MsgBox(myPerson.Enroll)

Both these calls to the Enroll method will work fine.

This might raise a host of questions. For example, could Student redefine the Enroll method so that it is not using the code in Person? The answer is yes. Could Person refuse to let someone instantiate it directly, instead forcing people to instantiate other classes that inherit it? Again, the answer is yes. You will see this and more as you examine more that you can do with inheritance.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.32.154