Tuesday, June 5, 2012

What is Polymorphisms?

Another primary concept of object-oriented programming is Polymorphism. It allows you to invoke derived class methods through a base class reference during run-time. This is handy when you need to assign a group of objects to an array and then invoke each of their methods. They won't necessarily have to be the same object type. However, if they're related by inheritance, you can add them to the array as the inherited type. Then if they all share the same method name, that method of each object can be invoked. This lesson will show you how to accomplish this.
OR: A SINGLE ENTITY represents multiple forms depending on the context.
We can divide the polymorphism into 2 types.
1. Static polymorphism (done by Method Overloading- answered after this artical)
2. Dynamic polymorphism (done by Method Over-riding answered after this)

1. Static Polymorphism
In Static Polymorphism, Which method is to be called is decided at compile-time only. Method Overloading is an example of Static Polymorphism.
Method overloading is a concept where we use the same method name many times in the same class, but different parameters. Depending on the parameters we pass, it is decided at compile-time only, which method is to Calles. The same method name with the same parameters is an error and it is a case of duplication of methods which c# does not permits. In Static Polymorphism decision is taken at compile time.
Example: Static Polymorphism
public Class StaticPolyDemo
{
public void display(int x)
{
Console.WriteLine (“Area of a Square:”+x*x);
}
public void display(int x, int y)
{
Console.WriteLine(“Area of a Square:”+x*y);
}
public static void main(String args[])
{
StaticPolyDemo spd=new StaticPolyDemo ();
Spd.display (5);
Spd.display (10, 3);
}
}
2. Dynamic Polymorphism
In this Mechanism by which a call to an overridden function is resolved at a Run-Time( not at Compile-time). If a Base Class contains method must be a Virtual method in C# to be overridden..
Example: Dynamic Polymorphism
Class Test
{
Public virtual void show()
{
Cosnsole.WriteLine (“From base class show method”);
}
}
Public Class DynamicPolyDemo1 : Test
{
Public override void show()
{
Console.WriteLine(“From Demo1 Class show method”);
}
}
Public Class DynamicPolyDemo2: Test
{
Public override void show ()
{
Console.WriteLine (“From Demo2 Class show method”);
}
Public static void main (String args[])
{
Test objtst;
int x;
//take value from users as input
if(x==1)
{
Objtst=new DynamicPolyDemo1();
}
else
Objtst=new DynamicPolyDemo2();
objtst.show();
}
}

Overloading: Define methods with same name , same return type with different parameters or with different datatypes or with different order of parameters.

Over-riding: Re-define method in the sub-class with same signature. One restriction is method modifier can't be more liberal than in parent class. (i.e. private in parent class and public in sub-class).



No comments:

Post a Comment