Wednesday, December 3, 2014

Polymorphism Simply !

If you think about the Greek roots of the term "Polymorphism", it should become obvious.
  • Poly = many: polygon = many-sided, polystyrene = many styrenes (a), polyglot = many languages, and so on.
  • Morph = change or form: morphology = study of biological form, Morpheus = the Greek god of dreams able to take any form.
So polymorphism is the ability (in programming) to present the same interface for differing underlying forms (data types).

If, for example, you have two classes: DogPet and CatPet that inherits form a parent class: Pet, like:

class Pet
{
    public virtual string GetPetSound()
    {
        return "Each Animal has its own different Sound.";
    }
}

class DogPet : Pet
{
    public override string GetPetSound()
    {
        return "Woof!";
    }
}

class CatPet : Pet
{
    public override string GetPetSound()
    {
        return "Meaw!";
    }
}

And you have defined the following instances and called a member function: GetPetSound, like:

Pet dog = new DogPet();
Pet cat = new CatPet();

string dog_sound = dog.GetPetSound();
string cat_sound = cat.GetPetSound();

Each individual type of pet can figure out the details on their own, allowing the code that uses it to focus on other things. This is how the Virtual keyword is related to Polymorphism.

Method Overloading is not a part of Polymorphism. However Method Overriding is indeed part of Polymorphism, as we did in the above example.

Some people consider Method Overloading a Compile Time Polymorphism where there are functions with same name and different parameters.
They also classify Method Overriding as a Run-Time Polymorphism where there are Functions in the extended class with same name and same parameters as in the base class, but with different behaviors.

Method Overloading Example:
public class A
{
    public void print(int x, int y)
    {
        Console.WriteLine("Parent Method");
    }
}

public class B : A
{
    public void child()
    {
        Console.WriteLine("Child Method");
    }

    public void print(float x, float y)
    {
        Console.WriteLine("Overload child method");
    }
}
Method Overriding Example:
public class A
{
    public virtual void print()
    {
        Console.WriteLine("Parent Method");
    }
}

public class B : A
{
    public void child()
    {
        Console.WriteLine("Child Method");
    }

    public override void print()
    {
        Console.WriteLine("Overriding child method");
    }
}

No comments: