Method Overriding in Java
In Java, Method Overriding is a feature that allows a subclass to provide a specific implementation of a method that is already defined in its parent class. The overridden method in the child class must have the same method signature as the one in the parent class.
Why Method Overriding?#
Method Overriding is used to achieve runtime polymorphism and to provide a specific implementation for a method in a derived class that differs from its base class.
Key Rules of Method Overriding#
- The method in the child class must have the same name as in the parent class.
- The method must have the same parameters as in the parent class.
- There must be an inheritance relationship (i.e., one class must be a subclass of another).
- The return type should be the same or covariant (subtype of the return type in the parent class).
- The access modifier cannot be more restrictive than the method in the parent class.
- Methods marked as
final
,static
, orprivate
cannot be overridden.
Example of Method Overriding#
Output:#
Using super
in Method Overriding#
The super
keyword can be used to call the overridden method of the parent class.
Output:#
Conclusion#
In this blog, we learned about Method Overriding in Java, its importance in achieving runtime polymorphism, and the rules associated with it. We also explored examples demonstrating overriding and how to use super
to call the parent class method. In the future blogs we will also cover difference between Method Overloading and Method Overriding in Polymorphism as it is important from the interview point of view.