Tuesday, March 8, 2016

Lesson 8

Outline

Chapter 12

Polymorphism

Another primary concept of object-oriented programming is Polymorphism. It allows you to invoke derived class methods through a base class reference during run-time. This is handy when you need to assign a group of objects to an array and then invoke each of their methods. They won't necessarily have to be the same object type.



In a previous lesson we discussed the inheritance aspects of the diagram above. Below is the code that supports the diagram above with a few properties to illustrate polymorphic behavior.

    class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string FullName
        {
            get { return FirstName + " " + LastName; }
        }
    }
    class Staff : Person
    {
        public int PayGrade { get; set; }
    }
    class Student : Person
    {
        public string Major { get; set; }
    }
    class Teacher : Staff
    {
        public string OfficeLocation { get; set; }
    }
    class Cleaner : Staff
    {
        public int WeeklyHours { get; set; }
    }


Polymorphism allows one object to "behave" like another in its inheritance tree. So in the above hierarchy a "teacher" object could behave like a "staff" object.

Suppose we had a method that took a staff object:

     public class Utilities
     {
          public void WorkWithStaff(Staff staffMember)
          {
               PayGrade = 5;
          }
     }


We could do the following:

Staff myStaff = new Staff();
Utilities myUtil = new Utilities();

myUtil.WorkWithStaff(myStaff);

Since myStaff is of type Staff then we can pass that object in as a parameter to our method. But due to the rules of polymorphism we can do this too:

Teacher myTeacher = new Teacher();
Utilities myUtil = new Utilities();

myUtil.WorkWithStaff(myTeacher );

Because Teacher has Staff in the object inheritance tree we can do this. Note, this only works upstream so Teacher can be Staff but Staff cannot be Teacher.

Also, while in the method WorkWithStaff, all objects passed into the method will behave as a staff object. In other words, inside the method we would not be able to access any of the Teacher attributes.

Polymorphism is a big topic. We will revisit this topic in a future lesson..




No comments:

Post a Comment