Polymorphism means one name many forms. It is the main feature of OOPs. Polymorphism is an ability to take more than one form but name will be the same. There are two types of polymorphism in NET.
Compile Time Polymorphism
When we create two or more method with the same name but different parameters or different sequence of parameters and the time of calling compiler decide on the time of compilation which method should be called on the basis of given arguments.
That is why it is called compile time polymorphism. We also call it static polymorphism.
It is implemented using overloaded methods and operators. Overloading process is called early binding. In compile time polymorphism I have implemented overloading concepts with an example as given below:
Example 1
See the following example and in that example I have created two Add methods whose name are same but parameters are different.
- using System;
-
- namespace DemoTest
- {
- class AddClass
- {
- public void Add(int a, int b)
- {
- int r = a + b;
- Console.WriteLine("Add two integer Number = " + r);
- }
- public void Add(string x, string y)
- {
- Console.WriteLine("Concatenation two string = " + x+y);
- }
- }
-
- class Program
- {
- static void Main(string[] args)
- {
-
- AddClass addClassObj = new AddClass();
- Console.WriteLine("Enter Two Integer values");
- int m = int.Parse(Console.ReadLine());
- int n = int.Parse(Console.ReadLine());
- addClassObj.Add(m, n);
-
-
- Console.WriteLine("Enter Two String values");
- string s1 = Console.ReadLine();
- string s2 = Console.ReadLine();
- addClassObj.Add(s1, s2);
- Console.ReadLine();
- }
- }
- }
Run Time Polymorphism When we create same name method in inherited class and what to override the functionality of base class, then we use “
Run Time Polymorphism”. It is called run time polymorphism because the compiler decides which method should be called on the runtime. This is achieved through the use of
virtual keyword with method.
To override the base class method, we create base class method as virtual and derived class method as override.
Example 2 See the following example where I have explained how can we override the base class method.
- using System;
-
- namespace DemoTest
- {
- class ClassA
- {
- public virtual void Show()
- {
- Console.WriteLine("This is Show from ClassA");
- }
- }
- class ClassB : ClassA
- {
- public override void Show()
- {
- Console.WriteLine("This is Show from ClassB");
- }
- }
- class ClassC : ClassA
- {
- public override void Show()
- {
- Console.WriteLine("This is Show from ClassC");
- }
- }
- class Program
- {
- static void Main(string[] args)
- {
- ClassA classAObj = new ClassA();
- classAObj.Show();
- classAObj = new ClassB();
- classAObj.Show();
- classAObj = new ClassC();
- classAObj.Show();
- Console.ReadLine();
- }
- }
- }
So, finally you learned what polymorphism is and how many types of polymorphism. You also see the two examples which are explaining the compile time polymorphism and run time polymorphism.