Polymorphism definition with example in C#.Net

Polimorphism

Definition 1: The ability to take more than one form. 
Definition 2: Same operation may work in different way on other classes. 

Basically polimorphism are two types: 
1. Compile time polymorphism: for example method overloading
2. Run time polymorphism: for example method overriding.

Compile time polymorphism:

Method Overloading

In this, calss is this having same method name and different arguments. This is check at compile time only. So we can call it as compile time polimorphism. 

class Compile
{
public string method(string first)
{ 
     return first; 
}

public string method()
{ 
      return "no argument";}
}
}

Run Time Polymorphism:

Def:  Method overriding occurs When the child class is having same method name with arguments count and type by one of its superclass. 

        class BaseClass
        {
            public virtual void OverrideExample() 
            { 
                Console.WriteLine("base method"); 
            }
        }

        class DerivedClass : BaseClass
        {
            public override void OverrideExample() 
            { 
                Console.WriteLine("derived method"); 
            }
        }

        class Test
        {
            static void Main(string[] args)
            {
                BaseClass a;
                DerivedClass b;

                a = new BaseClass();
                b = new DerivedClass();
                a.OverrideExample();  // output --> "base method"
                b.OverrideExample();  // output --> "derived method"

                a = new DerivedClass();
                a.OverrideExample();  // output --> "derived method"
                Console.ReadLine();
            }
        }
Share this post :

Post a Comment

Please give your valuable feedback on this post. You can submit any ASP.NET article here. We will post that article in this website by your name.

 
Support : Ranga Rajesh Kumar
Copyright © 2012. ASP.NET Examples - All Rights Reserved
Site Designed by Ranga Rajesh Kumar