Introduction
According to MSDN:
Polymorphism is often referred to as the third pillar of object-oriented programming, after encapsulation and inheritance. Polymorphism is a Greek word that means "many-shaped".
In simple terms, in Polymorphism an object can take make forms.
Note: To understand polymorphism, make sure you have understood the concepts of Inheritance. As we know that the Polymorphism can’t achieved without Inheritance.
Description:
Polymorphism can be achived in two ways, That is:
- Static Polymorphism or Compile time Polymorphism
Compile time polymorphism is nothing but the method overloading in C#. In simple terms we can say that a class can have more than one method with same name but with different number of arguments or different types of arguments or both.
Compile time polymorphism can be archived in Single Class.
Constructor can be overloaded.
Example
- namespace Polymorphism
- {
- class MyClass
- {
- public void show()
- {
- MessageBox.Show("This is 'Show' Without Argumant ");
- }
- public void show(int num1, string str1)
- {
- MessageBox.Show("This is 'Show' With 2 Argumant ");
- }
- public void show(string str1, int num1)
- {
- MessageBox.Show("This is 'Show' With 2 Argumant Difference in Sequence of Paramanters");
- }
- public void show(string str1, string str2)
- {
- MessageBox.Show("This is 'Show' With 2 Argumant but Different in Type ");
- }
- public void show(string str1, string str2, string str3)
- {
- MessageBox.Show("This is 'Show' With 3 Argumant Difference in Number of Paramanters");
- }
- }
- class AnotherClass
- {
- public void Display()
- {
-
- MyClass obj = new MyClass();
- obj.show();
- obj.show(1, "test");
- obj.show("text", 5);
- obj.show("AAA", "BBB", "CCC");
- obj.show("AAA", "XXX");
- }
- }
- }
- Dynamic Polymorphism or Runtime Polymorphism
Child class has the same method as of base class.
Dynamic Polymorphism can be archived using method overriding. Overriding means a derived class is implementing a method of its super class.
Example
- namespace Polymorphism
- {
- class ParentClass
- {
-
- public virtual void show()
- {
- MessageBox.Show("");
- }
- public virtual void Display()
- {
- MessageBox.Show("");
- }
-
- public void Disp()
- {
- MessageBox.Show("");
- }
- }
- class ChildClass: ParentClass
- {
-
- public override void show()
- {
- MessageBox.Show("");
- }
-
- public override void Display()
- {
- MessageBox.Show("");
- }
- }
- }
Important points
Polymorphism provides the functionality to Call Child class methods using instance of Parent class that is not there in Inheritance.
The “new” keyword is used to hide the method of parent or base class which we don’t own. This is called method hiding.