Ability to take more than one form is called polymorphism.
The polymorphism consist two words poly and morphism poly means “multiple” and
morphism means “form”.
Following are the types of polymorphism
-Compile time
polymorphism also called Early binding or overloading or static binding
-Run time polymorphism
also called late binding or overriding or dynamic binding
Compile time
polymorphism – In compile time polymorphism method name is same with
different parameter (signature)
The example of the compile time polymorphism is given below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace compile_time_poly
{
public class Class1
{
public void show(int a, int b)
{
MessageBox.Show((a + b).ToString());
}
public void show(int a, int b, int c)
{
MessageBox.Show((a + b + c).ToString());
}
}
}
Code on button click:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace compile_time_poly
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void
button1_Click(object sender, EventArgs e)
{
Class1 obj = new Class1();
obj.show(5, 10);
obj.show(5, 10, 15);
}
}
}
Output:
15
30
Run time polymorphism
– In run time polymorphism method name and parameter should be same. Run
time polymorphism is achieved by virtual and override keyword. The example of run
time polymorphism is given below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace compile_time_poly
{
public class Class1
{
public virtual void show(int a, int b)
{
MessageBox.Show((a + b).ToString());
}
public class class2 : Class1
{
public override void show(int a, int b)
{
MessageBox.Show((a + b).ToString());
}
}
}
}
Button click code :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace compile_time_poly
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void
button1_Click(object sender, EventArgs e)
{
Class1 obj = new Class1();
obj.show(5, 10);
obj.show(5, 15);
}
}
}
Output:
15
20