The Rules of Overriding
What you'll learn: You'll understand the specific rules Java enforces when you override a method from a superclass.
Now that you know what method overriding is—redefining a superclass method in a subclass—you need to learn the strict rules Java enforces to ensure safe overriding.
The Four Core Rules
When you override a method, Java requires you to follow these constraints:
1. Same Method Name
The overriding method must have the exact same name as the method in the superclass. bark() in the subclass must match bark() in the superclass.
2. Same Parameter List
The parameters must match exactly—same number, same types, same order. If the superclass method has (String name, int age), your override must too. Different parameters? That's overloading, not overriding.
3. Compatible Return Type
The return type must be either the same or a subtype (covariant return). If the superclass returns Animal, you can return Animal or Dog (if Dog extends Animal), but not String or something unrelated.
4. Not More Restrictive Access
You cannot make the overriding method less accessible. If the superclass method is public, your override must be public—not protected or private. You can go the other way (make it more accessible), but that's rare.
Why These Rules?
Think of it like a contract: the superclass promises certain behavior, and the subclass must honor that promise. If a public method suddenly became private in a subclass, code expecting to call it would break. If parameters changed, it wouldn't be the same method anymore.
Key Takeaway: Method overriding requires the same name and parameters, a compatible return type, and equal or greater accessibility—these rules ensure type safety and preserve the superclass contract.