Chapter 16 Inheriting Forms and Creating Base Classes 409
or methods to the derived (child) class to distinguish it from the base class. I realize that
this may be sounding a bit abstract, so let’s try an example.
In the following exercise, you’ll modify the My Person Class project so that it stores information
about new teachers and the grades they teach. First, you’ll add a second user-defined class,
named Teacher, to the Person class module. This new class will inherit the FirstName property,
the LastName property, and the Age method from the Person class and will add an additional
property named Grade to store the grade in which the new teacher teaches.
Use the Inherits keyword
- Click the Person .vb class in Solution Explorer, and then click the View Code button.
- Scroll to the bottom of the Code Editor so that the insertion point is below the End
Class statement.
As I mentioned earlier, you can include more than one class in a class module, so long
as each class is delimited by Public Class and End Class statements. You’ll create a class
named Teacher in this class module, and you’ll use the Inherits keyword to incorporate
the method and properties you defined in the Person class. - Type the following class definition in the Code Editor. As before, after you type the Get
keyword and press ENTER, some of the Property structure will be provided for you:
Public Class Teacher
Inherits Person
Private Level As Short
Public Property Grade() As Short
Get
Return Level
End Get
Set(ByVal value As Short)
Level = value
End Set
End Property
End Class
The Inherits statement links the Person class to this new class, incorporating all of its
variables, properties, and methods. If the Person class were located in a separate module
or project, you could identify its location by using a namespace designation, just as you
identify classes when you use the Imports statement at the top of a program that uses
classes in the .NET Framework class libraries. Basically, I’ve defined the Teacher class as
a special type of Person class—in addition to the FirstName and LastName properties, the
Teacher class has a Grade property that records the level at which the teacher teaches.
Now you’ll use the new class in the Button1_Click event procedure.
- Display the Button1_Click event procedure in Form1.
Rather than create a new variable to hold the Teacher class, I’ll just use the Employee
variable as is—the only difference will be that I can now set a Grade property for the
new employee.