Types of Polymorphism
1) Static or Compile time Polymorphism
Which method is to be called is decided at compile-time only. Method overloading is an example of this. 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. The same method name with the same parameters is an error and it is a case of duplication of methods which c# does not permit. In Static Polymorphism decision is taken at compile time.
public Class StaticDemo
{
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[])
{
StaticDemo spd=new StaticDemo();
Spd.display(5);
Spd.display(10,3);
}
}
2) Dynamic or Runtime Polymorphism.
Run time Polymorphism also known as method overriding. 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 a method that is overridden. Method overriding means having two or more methods with the same name, same signature but with different implementation. In this process, an overridden method is called through the reference variable of a superclass, the determination of the method to be called is based on the object being referred to by reference variable.
What is polymorphism? Poly means many. So how can we take this definition in .NET context. Well we can apply this to class’s ability to share the same methods (actions) but implement them differently.
Suppose we have a method in a class to add numbers,
public class calculation
{
public int add(int x, int y)
{
return x+y;
}
}
So to perform addition of three numbers, we need similar add method but with different parameter
public class calculation
{
public int add(int x, int y)
{
return x+y;
}
public int add(int x, int y,int z)
{
return x+y+z;
}
}
So we can that class is sharing the same methods (actions) but implement them differently.
Now this is an example when we are sharing method name and implementing them differently, let’s take a scenario where implementation is in some derived class.
For instance, say we create a class called Shape and this class has a method called .Area () which calculates area. Then we create two subclasses, using inheritance, of this Shape class. One called Square, the other called Circle. Now obviously a square and circle are two entirely different shapes, yet both classes have the .Area() method. When the Square.Area() method is called it will calculate area of a square. When the Circle.Area() method is called, it will calculate area of a circle. So both classes can use the same methods but implement them differently.