Fremus.co.za

Demistifying Life and Web Development

C# OOP Concepts, Polymorphism

There are three very basic OO concepts that apply to most OO programming languages today:

  • Inheritance / Generalization / Specialization
  • Encapsulation
  • Polymorphism

The concept I am going to discuss here is polymorphism. Polymorphism as a concept can be taken from the concept of encapsulation, which states that an object is a complete thing that hides itself from other objects. Thus the other objects that have a relationship (possibly inheritance) with that object do not get to see the implementation details of the members from that object. In its simplest form polymorphism basically takes a method from an inheriting class, uses the same method name, but implements it in its own way.

A good analogy of this concept is to think of a telephone company that rents out telephone lines. The telephone company will send calls through to your line without knowing how your telephone device will react to that phone call. All the telephone company knows is that it needs to send the call through to your line, and the details of how you handle it is completely hidden. Your ring tone could be very different from a neighbours’ ring tone. I got this analogy from Jesse Liberty’s book, Programming C# 3.0, 5th Edition and I thought it explains two important OO concepts, encapsulation and polymorphism very well.

Polymorphism is implemented in C# by using the virtual keyword in the parent class and by using the override keyword in the child class:

namespace UsingVirtualMethods2
{
    class Program
    {
        static void Main(string[] args)
        {
            TelephoneMessage myMsg = new TelephoneMessage();
            TelephoneReceiver myRec = new TelephoneReceiver();
            myMsg.InterpretMessage();
            myRec.InterpretMessage();
        }
    }
    class TelephoneMessage
    {
        public virtual void InterpretMessage()
        {
            Console.WriteLine("This is the message coming through");
        }
    }
    class TelephoneReceiver : TelephoneMessage
    {
        public override void InterpretMessage()
        {
            Console.WriteLine("I have received your message and am interpreting it");
        }
    }
}

From the code above you can see that I use the virtual keyword in the TelephoneMessage class and then override it in the TelephoneReceiver class. TelephoneReceiver inherits from TelephoneMessage. I then create two instances of each class in the main method and call the InterpretMessage() method for each instance. This simple example actually illustrates basic usage of the three concepts mentioned earlier. usingvirtualmethods2

  • Share/Bookmark
posted by fr3dr1k in C# and have No Comments
Get Adobe Flash playerPlugin by wpburn.com wordpress themes