POLYMORPHISM

Roughly speaking, polymorphism means treating one object as another. In OOP terms, it means that you can treat an object of one class as if it were from a parent class.

For example, suppose that Employee and Customer are both derived from the Person class. Then you can treat Employee and Customer objects as if they were Person objects because, in a sense, they are Person objects. They are specific types of Person objects. After all, they provide all of the properties, methods, and events of a Person object.

Visual Basic enables you to assign a value from a child class to a variable of the parent class. In this example, you can place an Employee or Customer object in a Person variable, as shown in the following code:

Dim emp As New Employee   ' Create an Employee.
Dim cust As New Customer  ' Create a Customer.
Dim per As Person         ' Declare a Person variable.
per = emp                 ' Okay. An Employee is a Person.
per = cust                ' Okay. A Customer is a Person.
emp = per                 ' Not okay. A Person is not necessarily an Employee.

One common reason to use polymorphism is to treat a collection of objects in a uniform way that makes sense in the parent class. For example, suppose that the Person class defines the FirstName and LastName fields. The program could define a collection named AllPeople and add references to Customer and Employee objects to represent all the people that the program needs to work with. The code could then iterate through the collection, treating each object as a Person, as ...

Get Visual Basic 2012 Programmer's Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.