Method
Overriding in Java
Learn how subclasses redefine inherited methods to provide specialized behavior, and master the @Override annotation for safer code.
What is Method Overriding?
When a subclass provides its own implementation of a method that is already defined in its parent class, we call that method overriding. The subclass method replaces the inherited version at runtime.
Why Override Methods?
Inheritance: The Foundation
Rules of Overriding
The @Override Annotation
@Override is an annotation you place above a method to tell the compiler: "I intend this method to override a parent method." If the signature doesn't match any parent method, the compiler throws an error instead of silently creating a new method.
Overriding vs Overloading
| Overriding | Overloading | |
|---|---|---|
| Classes involved | Parent and child | Same class (or child) |
| Method name | Same | Same |
| Parameters | Must be identical | Must differ |
| Return type | Same or covariant | Can differ |
| Binding | Runtime (dynamic) | Compile-time (static) |
| @Override | ✓ Applies | ✕ Does not apply |
How to Override a Method
Example 1: Basic Override
Example 2: Polymorphism in Action
Example 3: Calling super
Covariant Return Types
Since Java 5, an overriding method can return a subtype of the parent method's return type. This is called a covariant return type.
Access Modifier Rules
What You Cannot Override
Common Mistakes
Summary Checklist
| Requirement | Valid Override | Invalid Override |
|---|---|---|
| Method name | Identical | Different name |
| Parameters | Identical | Changed types/count |
| Return type | Same or covariant | Unrelated type |
| Access | Same or wider | More restrictive |
| Parent method | Non-static, non-final, non-private | static / final / private |
| @Override | Recommended always | Omitted (risky) |
Question 1 of 5
Which of the following is required for a valid method override in Java?
Question 2 of 5
What happens if you add @Override to a method that does not actually override a parent method?
Question 3 of 5
A parent class has: protected void draw(). Which of these is a valid override in the child class?
Question 4 of 5
Given:
If Cat overrides speak(), which version of speak() is called?
Question 5 of 5
What does super.methodName() do inside an overriding method?