Qus : What is Polymorphism ?
Ans : 1. Polymorphism means one name many forms.
2. Many forms of a single object is called Polymorphism.
3. In Polymorphism poly means “multiple” and morph means “forms” so polymorphism means many forms
In polymorphism :
1. We will declare methods with same name and different parameters in same class OR
2. Declare methods with same name and same parameters in different classes.
Typies :
1. Overloading (Called as Early Binding or Overloading or static binding or Compile Time)
2. Overriding (Called as Late Binding or Overriding or dynamic binding or Run Time)
Description :
1. Overloading :- Overloading or Compile time polymorphism means declare methods with same name but different signatures.
Advantages : We will perform different tasks with same method name.
Example :
public class Calculation
{
public void Add(int n1, int n2)
{
Console.WriteLine(n1 + n2);
}
public void Add(int n1, int n2, int n3)
{
Console.WriteLine(n1 + n2 + n3);
}
}
2. Overriding :- Overriding or Run time polymorphism means declare same method names with same signatures.
=> We can override a method in base class (virtual) by creating similar function in derived class (override) this can be achieved by using inheritance principle and using “virtual & override” keywords.
Example :
public class Baseclass
{
public virtual string Call()
{
return "I am Base Class";
}
}
{
public override string Call()
{
return "I am Derived Class";
}
}
class Program
{
static void Main(string[] args)
{
Deriveclass oDC = new Deriveclass();
string a = oDC.Call();
Baseclass oBC= new Baseclass();
string b = oBC.Call();
Console.WriteLine("{0} \n {1}", a, b );
Console.ReadLine();
}
}
Output :
I am Derived Class
I am Derived Class