Covariance vs Parameter Contravariance
What you'll learn: Why Java allows return types to become more specific (covariant) when overriding methods, but doesn't allow parameter types to become more general (contravariant).
The Core Asymmetry
You've seen that Java supports covariant return types—when overriding a method, you can return a more specific type than the superclass version. But Java does not support contravariant parameter types—you cannot make parameters more general when overriding.
Here's why:
Covariant returns are safe because the caller expects at least the superclass return type. If you return something more specific, it still satisfies that contract. It's like ordering "a fruit" and getting "an apple"—perfectly acceptable.
Contravariant parameters would break type safety. If a superclass method accepts a specific parameter type, the caller might pass exactly that type. If a subclass could widen the parameter to something more general, the compiler couldn't guarantee what type would actually be handled.
Why Parameters Must Stay Invariant
class Animal {
void treat(Dog dog) {
// Treats dogs specifically
}
}
class Vet extends Animal {
// This would be contravariance—ILLEGAL in Java
// void treat(Animal animal) { ... }
// Parameters must match exactly or you're overloading, not overriding
@Override
void treat(Dog dog) {
// Must accept Dog, not any Animal
}
}
If Java allowed contravariance, a Vet object referred to as Animal could be passed a Dog, but the overriding method might try to handle any Animal—breaking the contract.
Key Takeaway: Java enforces covariant return types (more specific is safe) but requires invariant parameter types (must match exactly) to preserve type safety and polymorphic substitutability.