Java Method Overriding – Complete Guide with Examples
Learn Java method overriding, how to redefine parent class methods in child classes, its rules, advantages, and examples to implement runtime polymorphism in object-oriented programming.
Method Overriding in Java – Complete Detailed Tutorial
Method Overriding is a feature in Java that allows a child class to provide its own implementation of a method already defined in the parent class.
It is an essential concept for runtime polymorphism.
1. Key Points About Method Overriding
- Method must be inherited from parent class
- Method name, return type, and parameters must be the same
- Access level cannot be more restrictive than the parent method
@Overrideannotation is recommended (optional but improves readability)- Can override non-static and non-final methods only
2. Syntax of Method Overriding
3. Example – Basic Method Overriding
Output:
4. Example – Using Parent Reference for Child Object
- Runtime polymorphism occurs when parent reference points to child object
Output:
5. Rules of Method Overriding
- Method must be inherited
- Same method name and parameters
- Return type must be same (or covariant type)
- Private, static, and final methods cannot be overridden
- Access modifier: child ≥ parent (cannot reduce visibility)
6. Example – Access Modifiers in Overriding
Output:
7. Advantages of Method Overriding
- Supports runtime polymorphism
- Provides specific implementation for child class
- Enhances code maintainability and flexibility
- Allows dynamic method dispatch
8. Example – Using Method Overriding with Super Keyword
Output:
9. Summary
- Method Overriding → redefining parent method in child class
- Supports runtime polymorphism
- Rules: same method name, parameters, return type; cannot override final/static/private methods
- Enhances flexibility, reusability, and code maintainability