Lesson 8 / 25
Method Overriding Rules
Override methods correctly and know the rules about signatures, visibility and exceptions.
Replacing inherited behaviour
Overriding means a subclass provides its own implementation of a method inherited from its superclass, with the same name and parameter list. Java rules: the return type must be the same or a subtype (covariant return); the access modifier may be the same or less restrictive (a protected method can become public, not private); a checked exception thrown by the override must be the same as, or a subclass of, those declared by the parent (or none); static methods are not overridden but hidden; final methods cannot be overridden; and private methods are not inherited, so a method with the same name in the subclass is a new method. Always annotate overrides with @Override: the compiler then reports an error if the signature does not actually match, catching typos such as equals(Student s) instead of equals(Object o), which silently creates an overload rather than an override. Python overrides simply by defining a method with the same name; super().method() calls the parent's version.
Correct and accidental overrides
@Override turns a silent bug into a compile error.
class Animal {
protected String sound() { return "..."; }
public Animal reproduce() { return new Animal(); }
}
class Dog extends Animal {
@Override
public String sound() { return "Woof"; } // wider access: allowed
@Override
public Dog reproduce() { return new Dog(); } // covariant return: allowed
}
class Student {
String roll;
// BUG: this overloads, it does not override Object.equals(Object)
public boolean equals(Student other) { return roll.equals(other.roll); }
// with @Override the compiler would have rejected the line above;
// the correct signature is:
// @Override public boolean equals(Object o) { ... }
}A new recipe with the same name
Overriding is a branch restaurant serving its own version of the chain's signature dish under the same menu name. Customers order the same thing; the kitchen decides how it is cooked. Changing the dish's name by mistake creates a different dish nobody orders.
Quick check: Which change is allowed when overriding a public method in Java?
- Making the override private
- Changing the parameter types
- Throwing a broader checked exception
- Returning a subtype of the original return type
Answer
Returning a subtype of the original return type — Covariant return types are allowed; narrower access, different parameters or broader checked exceptions are not.