Runtime polymorphism or dynamic method dispatch is a feature of object-oriented programming languages that allows a subclass or derived class to provide a different implementation for a method that is already defined in its superclass or base class. This is achieved by creating a method with the same name and signature in the derived class as in the base class, and then replacing or “overriding” the implementation of the method in the derived class.
At runtime, when an object of the derived class is created and a method is called on it, the object will execute the overridden version of the method rather than the one inherited from the base class. This allows the derived class to customize the behavior of the method to suit its own needs, while still maintaining the same interface as the base class.
For example, consider a base class called “Shape” that has a method called “area” that calculates the area of the shape. A derived class called “Rectangle” might override the “area” method to provide its own implementation that calculates the area of a rectangle using the length and width of the rectangle. When an object of the “Rectangle” class is created and the “area” method is called on it, the object will execute the overridden version of the method, which calculates the area of a rectangle.
In this way, runtime polymorphism allows an object to behave differently based on its type, even if the object is referred to through a base class reference. This can be useful for creating more flexible and reusable code, as it allows different types of objects to be used interchangeably without the need to write separate code for each type.
Read the full article here ...
Polymorphism - Md Asiful Haque
Top comments (0)