Course contentsShow
← Java
Lesson 471 of 2,87011. Polymorphism and Dynamic DispatchFree lesson

The Rules of Covariance

Learning the compile-time constraints: return types must be subtypes, not supertypes or unrelated types.

The Rules of Covariance

What you'll learn: You'll understand the compile-time rules that determine whether a return type change counts as valid covariance.


The Core Rules

In the previous lesson, you learned what covariant return types are—when an overriding method returns a more specific type than its superclass version. Now let's understand the rules Java enforces at compile time.

Rule 1: The return type must be a subtype
When overriding, your new return type must be the same as or a subclass of the original return type. You cannot use a supertype or an unrelated type.

Rule 2: No sideways moves
You can only move "down" the inheritance tree toward more specific types, never sideways to sibling classes or unrelated types.

Rule 3: Primitive types cannot be covariant
Covariance only works with reference types. If the superclass method returns int, the subclass must also return int—not long, not double, nothing else.


Why These Rules Exist

Think of covariance like a contract guarantee. If a superclass promises "this method returns an Animal," a subclass can strengthen that promise to "this method returns a Dog" (since every Dog is an Animal). The caller still gets what they expected—or better.

But if the subclass tried to return Vehicle (a supertype) or Cat (a sibling type), the promise would be broken. A caller expecting an Animal might receive something incompatible.


The Compile-Time Check

Java verifies these rules at compile time. If you violate them, you'll get a compiler error like:

incompatible types: Cat cannot be converted to Dog

The compiler ensures type safety—no surprises at runtime.


Key Takeaway:
Covariant return types must be subtypes (more specific) than the original—never supertypes, sibling types, or primitives changing type.