Overriding a method with different return types in java?

You can return a different type, as long as it’s compatible with the return type of the overridden method. Compatible means: it’s a subclass, sub-interface, or implementation of the class or interface returned by the overridden method.

And that’s logical. If a method returns an Animal, and your derived class returns a Cow, you’re not breaking the contract of the superclass method, since a Cow is an Animal. If the derived class returns a Banana, that isn’t correct anymore, since a Banana is not an Animal.

Leave a Comment