Jun 27

What is Polymorphisms?

Polymorphism means one interface and many forms. Polymorphism is a characteristics of being able to assign a different meaning or usage to something in different contexts specifically to allow an entity such as a variable, a function or an object to have more than one form.

There are two types of Polymorphism.
Compile time: function or operator overloading
Runtime: Inheritence & virtual functions


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.
– Example of Method Overloading:
class A1
void hello()
{ Console.WriteLine(“Hello”); }

void hello(string s)
{ Console.WriteLine(“Hello {0}”,s); }

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();
Hello from Child.

Permanent link to this article: http://zappmania.in/2012/06/27/what-is-polymorphisms.htm

Leave a Reply

Your email address will not be published.