One function behaves different forms.In other words, "Many forms of a single object is called Polymorphism."
Static polymorphism is object during compile time is called early binding. It is also called static binding. There are two type of static polymorphism:
public class Calculation
{
//Method overloading here because both method name are same
//This method will take 2 parameter
public int Add(int num1, int num2)
{
return num1 + num2;
}
//This method will take 3 parameter
public double Add(int num1, int num2, int num3)
{
return num1 + num2 + num3;
}
}
Dynamic Polymorphism (Run Time Polymorphism):-
Dynamic polymorphism also called as late binding or method overriding or Run time polymorphism. Method overriding means same method names with same signatures.
Dynamic polymorphism is implemented by abstract classes and virtual functions.
Abstract classes contain abstract methods, which are implemented by the derived class.The derived classes have more specialized functionality.
Example :
namespace ConsoleApplication1
{
//Abstract Calss
abstract class Shape
{
//Abstract Method in abstract class
public abstract int Area();
//Virtual Method in abstract class
public virtual void Sample()
{
Console.WriteLine("Base Class");
}
}
//Derived Class
class Rectangle : Shape
{
private int length;
private int width;
public Rectangle(int a = 0, int b = 0)
{
length = a;
width = b;
}
//Abstract Method override in Derived Class
public override int Area()
{
Console.WriteLine("Rectangle class area :");
return (width * length);
}
//Virtual Method override in Derived Class
public override void Sample()
{
Console.WriteLine("Derived Class");
}
}
class Program
{
static void Main(string[] args)
{
//Create object Rectangle Class
Rectangle objRectangle = new Rectangle(10, 7);
//Call Abstract Method
double a = objRectangle.Area();
Console.WriteLine("Area: {0}", a);
//Call Virtual Method
objRectangle.Sample();
Console.ReadKey();
}
}
}