Polymorphism is a concept in computer science that refers to the ability of an object or function to take on multiple forms. In object-oriented programming, polymorphism is achieved through inheritance and method overloading.
Here is a real-life example of polymorphism:
Imagine you have a shape class with a method called “area()” that calculates the area of the shape. You can then create subclasses for different types of shapes (such as circles, squares, and triangles), each with their own implementation of the “area()” method. When you create an instance of one of these subclasses and call the “area()” method, the correct implementation will be used based on the type of shape you created.
For example:
class Shape {
public:
virtual double area() = 0; // pure virtual function
};
class Circle : public Shape {
public:
Circle(double r) : radius(r) {}
double area() { return 3.14 * radius * radius; }
private:
double radius;
};
class Square : public Shape {
public:
Square(double s) : side(s) {}
double area() { return side * side; }
private:
double side;
};
int main() {
Shape* shapes[2];
shapes[0] = new Circle(5);
shapes[1] = new Square(10);
for (int i = 0; i < 2; i++) {
cout << "Area: " << shapes[i]->area() << endl;
}
return 0;
}
In this example, the “area()” method is polymorphic because it can take on different forms based on the type of shape it is being called on. When the “area()” method is called on a Circle object, it will use the implementation for calculating the area of a circle. When it is called on a Square object, it will use the implementation for calculating the area of a square. This allows us to write code that can handle multiple types of shapes without having to write separate code for each type.