Friday, November 30, 2012

difference between static polymorphism and dynamic polymorphism



Static Polymorphism

Static Polymorphism means “Compile” time polymorphism or “Early binding”.

     Method Overloading is an example of Static Polymorphism, where method name is same with different parameters and implementation.

Dynamic polymorphism

Dynamic polymorphism means “Runtime” time polymorphism or “Late binding”.

    Method Overriding is an example of Dynamic Polymorphism, where the base class method is overridden by override keyword and its implementation is also changed.

Example: -
Below is the simple code snippet for Method Overloading.
public class StaticPoly
{
public void Display(int x)
{
Console.WriteLine("Value of x:"+x);
}
public void Display(int x, int y)
{
int z = 0;
z = x + y;
Console.WriteLine("Addition of x and y is:"+ z);
}
static void Main(string[] args)
{
StaticPoly Obj = new StaticPoly();
Obj.Display(10);
Obj.Display(10,3);
Console.ReadLine();
}
}

Example: -
Below is the simple code snippet for Method Overriding.
class A
{
public virtual void Display()
{
System.Console.WriteLine("Base Class A::Display");
}
}
class B : A
{
public override void Display()
{
System.Console.WriteLine("Derived Class B::Display");
}
}
class Demo
{
public static void Main()
{
A b;
b = new A();
b.Display();
b = new B();
b.Display();
Console.ReadLine();
}
}

No comments:

Post a Comment