Wednesday 10 September 2014

Polymorphism in c# with example

Polymorphism:

Polymorphism is one of the fundamental concepts of OOP.
It allows you to invoke methods of derived class through base class reference during runtime. It has the ability for classes to provide different implementations of methods that are called through the same name.

Types of Polymorphism:

There are 2 types of Polymorphism namely
1.Compile time polymorphism (or) Overloading
2.Runtime polymorphism (or) Overriding

Compile Time Polymorphism:

Compile time polymorphism is method and operators overloading. It is also called early binding.
Method with same name but with different arguments is called method overloading.
In method overloading, method performs the different task at the different input parameters.

Example: 

using System;

namespace ConsoleApplication2
{
   
    public class A1
    {
        public void hello()
        {
            Console.WriteLine("Hello");
        }

        public void hello(string s)
        {
            Console.WriteLine("Hello {0}", s);
        }
    }

    class Program
    {
      
        public static void Main(string[] args)
        {
            A1 obj = new A1();
            obj.hello();
            obj.hello("Welcome");
            Console.ReadLine();
           
        }

    }
}

Runtime Time Polymorphism:
Runtime time polymorphism is done using inheritance and virtual functions. Method overriding is called runtime polymorphism. It is also called late binding.
Method overriding occurs when child class declares a method that has the same type arguments as a method declared by one of its superclass.
When overriding a method, you change the behavior of the method for the derived class. Overloading a method simply involves having another method with the same prototype.
Method overloading has nothing to do with inheritance or virtual methods.

Example: 

using System;

namespace ConsoleApplication2
{

    class Program
    {
        public class parent
        {
            public virtual void hello()
            {
                Console.WriteLine("Hello from Parent");
            }
        }

        public class child : parent
        {
            public override void hello()
            {
                Console.WriteLine("Hello from Child");
            }
        }

        public static void Main(string[] args)
        {
            parent objParent = new child();
            objParent.hello();
            Console.ReadLine();
        }

    }
}


0 comments:

Post a Comment