Covariant Returns with Interfaces
What you'll learn: How to use interface subtypes as covariant return types when overriding methods.
Just as you can override a method to return a more specific class type, you can also return a more specific interface type. If a superclass method returns an interface, your subclass override can return any subtype (more specific implementation) of that interface.
The Core Idea
When a parent class or interface declares a method returning an interface type like Comparable or Iterable, you can override it to return a more specific interface that extends the original one. The override must still be compatible—just more precise.
This works because interfaces form a type hierarchy through extension. If SortedSet extends Set, then returning a SortedSet where Set was expected is perfectly valid through covariance.
Simple Example
interface Animal { }
interface Dog extends Animal { }
class AnimalShelter {
Animal getAnimal() {
return null; // placeholder
}
}
class DogShelter extends AnimalShelter {
@Override
Dog getAnimal() { // Covariant: Dog is subtype of Animal
return null; // would return actual Dog implementation
}
}
Here, Dog (an interface) extends Animal (another interface). The override in DogShelter legally narrows the return type from Animal to Dog.
Why This Matters
Clients of DogShelter automatically get the more specific Dog type without casting. The compiler knows more about what you're getting back, making your code safer and cleaner.
Key Takeaway: You can override methods to return more specific interfaces, not just classes—covariance applies to the entire type hierarchy, including interface inheritance chains.