We can add new data and methods to a class through inheritance. But what if we want our derived class to inherit a method from the base class and have a different implementation for it? That is when polymorphism, a fundamental concept in the OOP paradigm, comes into play.
Example
Consider the example of a Shape class, which is the base class while many shapes like Rectangle and Circle extending from the base class are derived classes. These derived classes inherit the getArea() method and provide a shape-specific implementation, which calculates its area.
Rectangle and circle inherit from shape
Implementation
We will be implementing the parent class first, and then the child classes.
Shape class
The Shape class has only one public method called getArea().
Let’s look at the implementation of the Shape class: