Polymorphism means "many forms", also can be said "one interface and many functions"
Inheritance allows the use of parent class members, Polymorphism makes the same methods work in a different way. Means method signature remains the same but the implementation may vary according to the need.
There are two forms we can achieve polymorphism
- Static Polymorphism
- Dynamic Polymorphism
In, Static Polymorphism we have the same method with multiple definitions. Method parameters or return types must differ to achieve polymorphism.
class Print
{
public void PrintNumber(int val)
{
Console.WriteLine(val);
}
public void PrintNumber(string val)
{
Console.WriteLine(val);
}
}
The above example contains the same method PrintNumber() with different parameters, so here we client is able to pass either int to string to print the same. This is called static polymorphism.
In Dynamic Polymorphism, With the help of Abstract classes and Virtual methods, you can achieve dynamic polymorphism. As we know Abstract classes have an abstract method that would require to declare an implementation in derived classes.
Point to remember,
- Instance creation is not allowed of an abstract class
- Abstract methods can be defined in abstract classes
- Sealed classes can not be inherited hence you can not declare an abstract class as Sealed.
abstract class Bird
{
public virtual void Sound()
{
Console.WriteLine("Bird Sound");
}
}
class Dove : Bird
{
public override void Sound()
{
Console.WriteLine("Coo Coo");
}
}
class Rooster : Bird
{
public override void Sound()
{
Console.WriteLine("cock-a-doodle-doo");
}
}
//Calling class method
Bird myBird = new Bird(); //This will create a bird object
Bird myDove = new Dove(); //This will create a dove object
Bird myRooster = new Rooster(); //This will create a rooster object
//Calling their methods
myBird.Sound(); //This returns Bird Sound from base class
myDove.Sount(); // This returns Coo Coo from the Dove class
myRooster.Sound(); //This returns cock-a-doodle-doo from Rooster class
The above example contains an abstract class Bird and Primary method definition with a virtual keyword which allows its child class to override the same method and make its own implementation. This is called a dynamic polymorphism as at runtime object comes to know which one to call.
When to use Polymorphism?
- This allows reusability in code
- The class extension is allowed using Inheritence so no change in the existing implementation
- Respective clients have their own method definition so it won't affect existing clients