Polymorphism
Definition
Polymorphism refers to something that has many forms/shapes/behaviours
which comes from word poly means many and morph means forms, as we know no single form has an overall advantage and in softwares we need to cover wide variety of use cases, so that we can modularize our software which can behave in many forms.
Types of Polymorphism
-
Runtime Polymorphism
- Runtime polymorphism, also referred to as dynamic polymorphism, occurs during runtime and is not determined by the compiler. In this type of polymorphism, the specific form or behavior to be executed is decided based on the actual execution of the program
- Runtime polymorphism is achieved through
method overriding
which uses inheritence in whichsubclass and superclass
has function withsame name
with same number and types of parameters but differs in implementation.
-
Compile Time Polymorphism
- Compile time polymorphism, also reffered to as static polymorphism, occurs during the compilation phase of a program. In this type of polymorphism, the compiler determines the specific shape or value that an entity will take during compilation.
- Compile time polymorphism is achieved through
method overloading
in this there are more than onefunction/behaviour
whose names are same but differ from each other on the basis of input parameters.
Implementation of Compile Time Polymorphism
- Java
- Other
class Area{
int area(int height,int width){
return height*width;
}
int area(int radius){
return (int)(3.14 * radius * radius);
}
}
public class Main {
public static void main(String[] argv){
// compile-time/static/early polymorphism also known as method overloading and operator overloading
Area area_object = new Area();
// when we want to calculate the area which has width and height
System.out.println(area_object.area(2,4));
// when we want to calculate the area of circle
System.out.println(area_object.area(10));
}
}
currently no other languages supported
Implementation of Run Time Polymorphism
- Java
- Other
class GeometricShape {
public double area(double side) {
return side;
}
}
class SquareDimension extends GeometricShape {
public double area(double side) {
return side * side;
}
}
class SquareCubeDimension extends GeometricShape {
public double area(double side) {
return 6 * side * side;
}
}
public class Main {
public static void main(String[] argv) {
// runtime/late binding/dynamic polymorphism (overriding)
GeometricShape dimension2D = new SquareDimension();
System.out.println("Area in 2D: " + dimension2D.area(2)); // -> return 4.0
GeometricShape dimension3D = new SquareCubeDimension();
System.out.println("Area in 3D: " + dimension3D.area(2)); // -> return 24.0
}
}
currently no other languages supported