Polymorphism
Polymorphism meaning "one name many forms", which is also referred to as the fourth pillar of object-oriented programming. "Poly" means many and "morph" means forms. Polymorphism provides the ability to a class to have multiple implementations with the same name.
Contents
Types of Polymorphism
Polymorphism can be static or dynamic. In static polymorphism, the response to a function is determined at the compile time. In dynamic polymorphism, it is decided at run-time.
Static Polymorphism
Static polymorphism is also known as Early Binding. We can achieve this by Method overloading. In overloading, the method / function has a same name but different signatures (types and/or the number of arguments and/or order of arguments). It is also known as Compile Time Polymorphism because the decision of which method is to be called is made at compile time.
Static Polymorphism Example
class Program { static void Main(string[] args) { Shapes _Shapes = new Shapes(); _Shapes.calculateArea(3); _Shapes.calculateArea(3, 4); Console.ReadLine(); } } class Shapes { public Shapes() { Console.WriteLine("Class : Shapes"); } public void calculateArea(double radius) { Console.WriteLine("Area of circle : " + ((3.14) * radius * radius).ToString()); } public void calculateArea(double length, double width) { Console.WriteLine("Area of rectangle : " + (length * width).ToString()); } }
Dynamic Polymorphism
Dynamic Polymorphism is also known as Runtime Polymorphism / Late Binding. It can be achieved by method overriding. In this mechanism / process, an overridden method is called through the reference variable of a super-class, the determination of the method to be called is based on the object being referred to by reference variable.
Dynamic Polymorphism Example
class Program { static void Main(string[] args) { Shapes _Shapes = new Square(); Shapes _Shapes1 = new Circle(); _Shapes.getType(); _Shapes1.getType(); Console.ReadLine(); } } class Shapes { public Shapes() { Console.WriteLine("Class : Shapes"); } public virtual void getType() { Console.WriteLine("Type : Shapes"); } } class Square : Shapes { public Square() { Console.WriteLine("Class : Square"); } public override void getType() { Console.WriteLine("Type : Square"); } } class Circle : Shapes { public Circle() { Console.WriteLine("Class : Circle"); } public override void getType() { Console.WriteLine("Type : Circle"); } }