Subroutines and functions enable you to reuse code by packaging it so other pieces of code can call it easily. By using inheritance, you can reuse code in another way: by making one class reuse the properties, methods, and events of another class.
In this lesson you learn how to use inheritance to make one class reuse the code of another. You also learn how polymorphism enables a program to treat an object of one class as if it belonged to another.
One way to understand inheritance is to realize that real-world things of one type may also be of another type. For example, an employee is also a person (despite what some managers may think). That means whatever attributes a person has, an employee has also. A person has a name, address, birthday, and so forth. An employee also has those things, in addition to some new ones such as a salary, job title, office number, and employee ID number.
Similarly, a manager is a type of employee. That means a manager has everything an employee does, which in turn means the manager has everything a person does.
In Visual Basic, classes provide a similar structure through inheritance. One class such as Employee
can inherit the properties, methods, and events of another class such as Person
.
This kind of inheritance enables you to reuse code in a new way because it means you don't need to write the same properties, methods, and events for the Employee
class that you already defined for the Person
class.
When you make one class inherit from another one, you derive the new class from the existing class. In that case, the new class is called the child class and the class from which it inherits is called the parent class.
You could build a Person
class with properties that all people have: FirstName, LastName, Street, City, State
, and Zip
. You could then derive the Employee
class from Person
and add the new properties Salary, JobTitle, MailStop
, and EmployeeId
.
Next, you could derive the Manager
class from Employee
and add new manager-related properties such as DepartmentName
and DirectReports
.
Syntactically, to make a class that inherits from another you add an Inherits
statement immediately after the Class
statement. For example, the following code shows definitions for a Person
class, an Employee
class that inherits from Person
, and a Manager
class that inherits from Employee
:
Public Class Person Public Property FirstName As String Public Property LastName As String Public Property Street As String Public Property City As String Public Property State As String Public Property Zip As String End Class Public Class Employee Inherits Person Public Property Salary As Decimal Public Property JobTitle As String Public Property MailStop As String Public Property EmployeeId As Integer End Class Public Class Manager Inherits Employee Public Property DepartmentName As String Public Property DirectReports As New List(Of Person) End Class
Polymorphism is a rather confusing concept that basically means a program can treat an object as if it were any class that it inherits. Another way to think of this is that polymorphism enables you to treat an object as if it were any of the classes that it is. For example, an Employee
is a kind of Person
so you should be able to treat an Employee
as a Person
.
Note that the reverse is not true. A Person
is not necessarily an Employee
(it could be a Customer
or some other unrelated person such as a Plumber
).
For a more detailed example, suppose you make the Person, Employee
, and Manager
classes, and they inherit from each other in the obvious way. Now suppose you write a method that takes a Person
as a parameter. Employee
inherits from Person
so you should be able to pass an Employee
into this method and the method should be able to treat it as a Person
. This makes intuitive sense because an Employee
is a Person
, just a particular kind of Person
.
Similarly, Manager
inherits from Employee
, so a Manager
is a kind of Employee
. If an Employee
is a kind of Person
and a Manager
is a kind of Employee
, then a Manager
must also be a kind of Person
, so the same method should be able to take a Manager
as its parameter.
This feature enables you to reuse code in ways that make sense. For example, if you write a method that addresses letters for a Person
, it can also address letters to Employees
and Managers
.
In this Try It, you get to experiment with classes, inheritance, and polymorphism. You build Person, Employee
, and Manager
classes. To test the classes, you build a simple program that creates instances of each class and passes them to a method that takes a Person
as a parameter.
You can download the code and resources for this Try It from the book's web page at www.wrox.com
or www.vb-helper.com/24hourvb.html
. You can find them in the Lesson25 folder of the download.
In this lesson:
Create a Person
class with properties FirstName, LastName, Street, City, State
, and Zip
. Give the class a GetAddress
method that returns the Person
's name and address properties as a string of the following form:
Alice Archer 100 Ash Ave Bugsville CO 82010
Derive an Employee
class from Person
. Add the properties EmployeeId
and MailStop
.
Derive a Manager
class from Employee
. Add a DepartmentName
property and a DirectReports
property of type List(Of Employee)
. Make a GetDirectReportsList
method that returns the names of the Manager
's direct reports, separated by new lines.
Make the main program create two Employee
s named Alice and Bob, a Manager
named Cindy who has Alice and Bob in her department, and a Person
named Dan.
Make a ShowAddress
method that takes a Person
as a parameter and displays the Person
's address.
On the main form, make buttons that call ShowAddress
for each of the people, passing the method the appropriate object.
Make a final button that displays Cindy's list of direct reports.
This example doesn't do anything fancy with the class's properties, so you can use auto-implemented properties.
The ShowAddress
method should take a Person
parameter even though some of the objects it will be passed are Employee
s or Manager
s.
Create a Person
class with properties FirstName, LastName, Street, City, State
, and Zip
. Give the class a GetAddress
method that returns the Person
's name and address properties as a string of the following form:
Alice Archer 100 Ash Ave Bugsville CO 82010
Make a new Person
class with code similar to the following:
Public Class Person Public Property FirstName As String Public Property LastName As String Public Property Street As String Public Property City As String Public Property State As String Public Property Zip As String ' Display the person's address. ' A real application might print this on an envelope. Public Function GetAddress() As String Return FirstName & " " & LastName & vbCrLf & Street & vbCrLf & City & " " & State & " " & Zip End Function End Class
Derive an Employee
class from Person
. Add the properties EmployeeId
and MailStop
.
Make the Employee
class similar to the following:
Public Class Employee Inherits Person Public Property EmployeeId As Integer Public Property MailStop As String End Class
Derive a Manager
class from Employee
. Add a DepartmentName
property and a DirectReports
property of type List(Of Employee)
. Make a GetDirectReportsList
method that returns the names of the Manager
's direct reports, separated by new lines.
Make the Manager
class similar to the following:
Public Class Manager Inherits Employee Public Property DepartmentName As String Public Property DirectReports As New List(Of Person) ' Return a list of this manager's direct reports. Public Function GetDirectReportsList() As String Dim result As String = "" For Each emp As Employee In DirectReports result &= emp.FirstName & " " & emp.LastName & vbCrLf Next emp Return result End Function End Class
Make the main program create two Employees
named Alice and Bob, a Manager
named Cindy who has Alice and Bob in her department, and a Person
named Dan.
Because the program's buttons need to access the objects, these objects should be stored in fields as in the following code:
' Define some people of various types. Private Dan As Person Private Alice, Bob As Employee Private Cindy As Manager
Add code to the main form's Load
event handler to initialize the objects. The following code shows how the program might create Alice's Employee
object:
' Make an Employee named Alice. Alice = New Employee() Alice.FirstName = "Alice" Alice.LastName = "Archer" Alice.Street = "100 Ash Ave" Alice.City = "Bugsville" Alice.State = "CO" Alice.Zip = "82010" Alice.EmployeeId = 1001 Alice.MailStop = "A-1"
Creating and initializing the other objects is similar. The only odd case is adding Alice and Bob as Cindy's employees as in the following code:
Cindy.DirectReports.Add(Alice) Cindy.DirectReports.Add(Bob)
Make a ShowAddress
method that takes a Person
as a parameter and displays the Person
's address.
Use code similar to the following:
' Display this Person's address. Private Sub ShowAddress(ByVal per As Person) MessageBox.Show(per.GetAddress()) End Sub
On the main form, make buttons that call ShowAddress
for each of the people, passing the appropriate object to the method.
Create the buttons' Click
event handlers. The following code shows the event handler that displays Cindy's address:
Private Sub btnCindyAddress_Click() Handles btnCindyAddress.Click ShowAddress(Cindy) End Sub
Note that the variable Cindy
is a Manager
but the ShowAddress
method treats it as a Person
. That's okay because Manager
inherits indirectly from Person
.
Make a final button that displays Cindy's list of direct reports.
This method simply calls the Cindy
object's GetDirectReportsList
method and displays the result:
Private Sub btnCindyReports_Click() Handles btnCindyReports.Click MessageBox.Show(Cindy.GetDirectReportsList) End Sub
Please select Lesson 25 on the DVD to view the video that accompanies this lesson.
Make Vehicle, Car, SportsCar
, and Truck
classes, giving them appropriate properties.
Figure 25-1 shows an inheritance diagram that illustrates the relationships between the Vehicle, Car, SportsCar
, and Truck
classes. Arrows point from each child class to its parent class. Draw a similar diagram to show the relationships between the Person, Employee, Manager, Secretary, Programmer, Executive
, and Customer
classes.
Implement the inheritance hierarchy you built in Exercise 2, giving each class a few reasonable properties. If you give the Executive
class a ReportingManagers
property that is a list of Managers
, can an Executive
have another Executive
as a reporting Manager
? (Look in the solution's Executive
class for the answer.)
You can find solutions to this lesson's exercises in the Lesson25 folder inside the download available on the book's web site at www.wrox.com
or www.vb-helper.com/24hourvb.html
.