Video in progress

Strong Junior 🧱 OOP and SOLID

When overriding a method, what restrictions apply to the return type, the access modifier and exceptions?

The signature must be the same; the return type can be the same or a subtype (covariant); the access modifier can't be narrowed, only widened; and checked exceptions can't be broader than those of the parent method.

📖 Answer

All the rules come from one idea: where the parent type is expected, the child object must work without problems (LSP).

class Repo {
    protected Number count() throws IOException { return 0; }
}

class UserRepo extends Repo {
    @Override
    public Integer count() { return 42; }            // correct: public is wider, Integer is a subtype of Number, no exception
}

class BadRepo extends Repo {
    // private Number count()                    // error: access is narrowed
    // Object count()                            // error: the return type is widened
    // Number count() throws Exception           // error: the checked exception is widened
}

A table to remember:

Element Allowed Forbidden
Return type The same or a subtype A supertype or another type
Access The same or wider Narrower
Checked exception The same, narrower, or none New or broader
Unchecked exception Any n/a
Primitive return type Exactly the same Even int → long is forbidden

Covariant return types are common with generics: overriding clone() to return the concrete class instead of Object is an example.