All topics
library
beginner

Method Overriding & @Override

Understand the rules for valid overrides and why @Override is non-negotiable.

Method overriding lets a subclass replace an inherited method's implementation. The JVM uses dynamic dispatch to call the correct version based on runtime type.

A franchise restaurant: headquarters defines the standard recipe. Each location can customize (override), but must serve the same dish name (same signature).

Key Concepts

1
Rules for valid override: 1. Same method name and exact parameter list. 2. Return type must be same or covariant (subtype). 3. Access modifier must be same or less restrictive. 4. Cannot throw broader checked exceptions than parent. 5. static, final, and private methods cannot be overridden.
2
@Override annotation is technically optional but always use it. It tells the compiler you intend to override — if the signature doesn't match, it flags an error instead of silently creating a new method.
3
Covariant return types (since Java 5): overriding method can return a more specific type. If Animal.clone() returns Animal, Dog.clone() can return Dog.
4
Bridge methods: the compiler generates synthetic methods for binary compatibility when generics and covariant returns interact.