What is a covariant return type in method overriding?
An overriding method may return a more specific type (a subclass) than the parent's method declared. Callers using the child type then avoid casting.
Explain it simply
If a parent method promises "I will give you an animal", a child may fairly promise "I will give you a dog", because a dog is an animal. Anyone expecting an animal is still satisfied, and anyone who knows it is a dog gets extra precision.
Example
class Animal {
Animal reproduce() { return new Animal(); }
}
class Dog extends Animal {
@Override
Dog reproduce() { return new Dog(); } // narrower return type is allowed
}
Dog d = new Dog();
Dog puppy = d.reproduce(); // no cast needed
Animal a = d;
Animal other = a.reproduce(); // still works through parent typeThe reverse is not allowed. A child cannot widen the return type, and for primitives the return type must be identical.
What to say in the interview
"Since Java 5, an overriding method can return a subtype of the parent's return type. It keeps the contract valid and saves callers from casting. Primitives and void must match exactly."
Common mistakes
- Trying to return a parent type from the child override.