24 Oct 2023
Method overriding in object-oriented programming (OOP) is the ability of a subclass to provide its own implementation of a method that is already defined in its superclass. This allows the subclass to customize the behavior of the method without modifying the original implementation.
Diagram:
Superclass (Parent) Subclass (Child)
| |
| |
Method Method (Overrides)
| |
| |
V V
Implementation Custom Implementation
Example1:
- Superclass (Parent): Shape
- Subclass (Child): Rectangle
- Method: CalculateArea()
The Shape superclass defines an abstract CalculateArea() method, which serves as a blueprint for calculating the area of different shapes. The Rectangle subclass overrides this method to calculate the area based on its specific formula (i.e., length × width).
This example demonstrates how different subclasses can inherit a common method from a superclass and provide their own custom implementation to suit their unique characteristics.
Example2:
-
Superclass (Parent): Shape
-
Subclass (Child): Circle
-
Method: CalculateArea()
The Shape superclass has an abstract
CalculateArea()method. The Circle subclass overrides this method to calculate the area based on its specific formula (e.g., πr^2).