Object Oriented Programming Pillar #3: Polymorphism

The third plank of OOP is a concept called Polymorphism. In my last post we went over Inheritance. Inheritance allows us to go from something generic, like an Employee, to something more specific, like a Manager or Peon. Polymorphism allows us to go in the reverse direction, treating something specific as something more generic.

Why would you want to do this? In our example, payroll would be a perfect example. Let’s first create our Peon class. We’ll also be using the Manager and Employee classes we have been using over the last few days.  

using System;

using System.Collections.Generic;

using System.Text;

 

namespace OOPDemo

{

  class Peon : Employee

  {

    public Peon(): base()

    {

    }

 

    public override string FullName()

    {

      string retval;

 

      if (base.FirstName.Length > 0)

        retval = base.FirstName.Substring(0, 1) + “. “ + base.Lastname;

      else

        retval = base.FirstName + ” “ + base.Lastname;

 

      return retval;

    }

  }

}

 

As you can see, Peon is pretty simple, I called the base constructor so I wouldn’t wind up homeless (see yesterday’s comments) and overrode the FullName method just because I could.

Now what we want is a routine that will call a method common to every Employee object. Here’s one I whipped up.  

    private void ShowName(Employee emp)

    {

      MessageBox.Show(emp.FullName(), “ShowName Method”);

    }

 

In the real world, we would probably be doing something here like call a “PayEmployee” method. PayEmployee is something we would do for all employees, regardless of whether they are a manager or a peon. For this example I’m just calling the FullName method, since we’ve been using it the last few days. Now we need to create our various objects and pass them to ShowName.

 

      Employee emp1 = new Employee();

      emp1.FirstName = “Carl”;

      emp1.Lastname = “Franklin”;

      this.ShowName(emp1);

 

      Manager mgr1 = new Manager(); 

      mgr1.FirstName = “Richard”;

      mgr1.Lastname = “Campbell”;

      this.ShowName(mgr1);

 

      Peon peon1 = new Peon();

      peon1.FirstName = “Mark”;

      peon1.Lastname = “Miller”;

      this.ShowName(peon1);

 

Here you can see I’ve created one Employee, one Manager, and one Peon object. But I can pass all three of them to the same ShowName method and treat them like Employees. Why? Because they are all descended from (or are) the Employee class. Polymorphism makes all this work.

You should note something very important here. If you actually run the program, you’ll see the following message boxes appear, in this order:

[Pic of Employee FullName]

ShowName with Employee

[Pic of Manager FullName]

ShowName with Manager

[Pic of Peon FullName]

ShowName with Peon

 

Do you see it? Even though within the ShowName method we are treating everything like an Employee, the compiler was smart enough to know they were not all Employees. Instead, it called the overridden method in the child class (Manager and Peon), not the one in the base class. This behavior is very important to understand. On one hand, it’s what makes Polymorphism so powerful, but if you are not expecting it, you can get bit.

Because this can get confusing, let’s see if I can relate this to a real world example. I have a wife and two daughters. Their base class might be “family member”, but their specific classes are wife (Ammie), daughter 1 (Raven) and daughter 2 (Anna).

On days where I might work from home, I can send family member a message (i.e. yell) “get daddy a Jolt cola”. The base implementation is open refrigerator, get soda, bring to daddy (that’s me). My wife Ammie just uses the base implementation of the “get daddy a Jolt cola” method.

My oldest daughter, Raven isn’t quite tall enough to reach the sodas on the top shelf, so she has to override the “get daddy a Jolt cola” method by adding a step to stand on a stool so she can reach them.

My youngest daughter, Anna is even shorter still, so her override calls for her to stand in a chair in order to reach the soda.

Now, in all three cases I simply call the “get daddy a Jolt cola” method of the “family member” object. When the individual object (Ammie, Raven or Anna) executes the “get daddy a Jolt cola” method, they each use their individual implementation to do so.

So where are some situations where Polymorphism would come in handy? Yesterday you may recall I said my classes in my Database Layer (often referred to as the DL) all descend from a common base class.

Within my program then, I can take all of my database objects and pass them into a “CloseConnection” method. The CloseConnection method does what it says, closes any database connections before exiting the program. Because of Polymorphism, it doesn’t matter what type of data object I’m dealing with (Purchase Order, Employee, Work Order, etc) they all need to close, and this lets me do it in an easy, consistent manner that’s easy to update and maintain.

Another real world example: I created a special combo box control to which I added some additional features. My new combo was descended from the standard combo box in the toolbox.

I then turned around and created four new combo boxes from my special base class combo. Each one was bound to a specific type of data, and I used these over and over in my application. Each one though had some common methods, such as Load and Reset.

When my form loaded, I passed each combo box to a method to load them. All this method did was called the load method for each box, and because I’d overridden the load method it called the correct Load for each type of combo box.

Over the last few days I’ve written on the basics behind Object Oriented Programming, using C# to demonstrate. You should understand I’ve only scratched the service as far as power and flexibility go, OOP is a big subject. But hopefully what I’ve discussed here will serve as a starting point for your OOP journey.

About these ads

3 Responses to “Object Oriented Programming Pillar #3: Polymorphism”

  1. Swarnava Banerjee Says:

    Nice Article ….explained practically …Keep up the good work .. :-)

  2. Dave Schinkel Says:

    It’s about time people start explaining this stuff in a real-world example. Good Work!

  3. ShaneVN Says:

    Thanks Arcane Code. Your site is so interesting. I like your lessons,it’s really easy to understand under your explanation.))


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 94 other followers

%d bloggers like this: