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 shown in the following code:

For Each per As Person In AllPeople
    Debug.WriteLine(per.FirstName & " " & per.LastName)
Next Per

You can only access the features defined for the type of variable you actually use to refer to an object. For example, if you use a Person variable to refer to an Employee object, you can only use the features defined by the Person class, not those added by the Employee class.

If you know that a particular object is of a specific subclass, you can convert the variable into a more specific variable type. The following code loops through the AllPeople collection and uses the TypeOf statement to test each object’s type. It uses DirectCast to convert the more general Person variable into a variable with a more specific class and then uses the new variable to perform class-specific tasks.

For Each per As Person In AllPeople
    If TypeOf per Is Employee Then
        Dim emp As Employee = DirectCast(per, Employee)
        ' Do something Employee-specific.
        ...
    ElseIf TypeOf per Is Customer Then
        Dim cust As Customer = DirectCast(per, Customer)
        ' Do something Customer-specific.
        ...
    End If
Next per
..................Content has been hidden....................

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