25 June 2012

Example of Polymorphism in .Net

What is Polymorphism?Polymorphism means same operation may behave differently on different classes.
Example of Compile Time Polymorphism: Method Overloading
Example of Run Time Polymorphism: Method Overriding

Example of Compile Time Polymorphism
Method Overloading- Method with same name but with different arguments is called method overloading.
- Method Overloading forms compile-time polymorphism.


Practical example of Method Overloading (Compile Time Polymorphism)

using System;

namespace method_overloading
{
    class Program
    {
        public class Print
        {
           
            public void display(string name)
            {
                Console.WriteLine("Your name is : " + name);
            }

            public void display(int age, float marks)
            {
                Console.WriteLine("Your age is : " + age);
                Console.WriteLine("Your marks are :" + marks);
            }
        }
       
        static void Main(string[] args)
        {

            Print obj = new Print();
            obj.display("George");
            obj.display(34, 76.50f);
            Console.ReadLine();
        }
    }
}

Example of Run Time Polymorphism
Method Overriding- Method overriding occurs when child class declares a method that has the same type arguments as a method declared by one of its superclass.
- Method overriding forms Run-time polymorphism.
- Note: By default functions are not virtual in C# and so you need to write “virtual” explicitly. While by default in Java each function are virtual.
- Example of Method Overriding:
Class parent
{
virtual void hello()
{ Console.WriteLine(“Hello from Parent”); }
}

Class child : parent
{
override void hello()
{ Console.WriteLine(“Hello from Child”); }
}

static void main()
{
parent objParent = new child();
objParent.hello();
}
//Output
Hello from Child.