Method Overriding & @Override
Method Overriding & @Override
Inheritance lets a child class reuse a parent's code. But what if the child needs to change how an inherited method works? That is exactly what method overriding is for. You write a new implementation of a parent method inside the subclass, and Java calls the child's version whenever the object is a child type.
What Is Method Overriding?
When a subclass provides its own definition of a method that already exists in a superclass, that is called overriding. The method in the subclass must have the same name, the same parameter list, and a compatible return type as the one in the superclass.
When you call speak() on a Dog object, Java runs the Dog version, not the Animal version — even if the variable type is Animal. (You will explore this in depth in the Polymorphism lesson.)
The @Override Annotation
Java lets you mark an overriding method with the @Override annotation. This is optional at runtime, but strongly recommended.
The Four Rules for Overriding
- Same method name — must match exactly.
- Same parameter list — number, types, and order. Different parameters make a new overloaded method, not an override.
- Compatible return type — either the same type or a subtype (covariant return; see below).
- Access modifier must not be more restrictive — if the parent declares
public, the child cannot declareprotectedorprivate. It may staypublicor become more open, but never narrower.
@Override to a method that only differs in parameters, the compiler will catch the mistake.
Covariant Return Types
Since Java 5, an overriding method may return a subtype of the parent's return type. This is called a covariant return type. It is useful when the parent returns a general type and the child can promise something more specific.
Callers of Circle.copy() get back a Circle without any casting. This improves type safety without breaking compatibility.
What Cannot Be Overridden
privatemethods — they are invisible to subclasses, so they cannot be overridden (only hidden).staticmethods — these are resolved at compile time, not runtime. A subclass can declare a static method with the same signature, but that is method hiding, not overriding.finalmethods — thefinalkeyword explicitly forbids overriding. You will learn aboutfinalin a later lesson.
A Complete Working Example
Each class defines what a bonus means for its own type. The same method call produces different results depending on the actual object — this is the power of overriding working alongside polymorphism.
Summary
- Overriding lets a subclass replace a parent method's implementation.
- Always add
@Override— the compiler catches typos and mismatches for you. - Follow the four rules: same name, same parameters, compatible (covariant) return type, and equal or wider access.
- Covariant return types let you return a more specific type without breaking the contract.
private,static, andfinalmethods cannot be overridden.