Win a copy of Functional Reactive Programming this week in the Other Languages forum!

# Benefits of covariant return types?

Kenny Johnson
Ranch Hand
Posts: 37
What are the benefits of covariant return types? Also, does anyone know a simple definition of the word covariant. I went to a few dictionary sites but the definitions were so math orientated that I got confused...

Scott Johnson
Ranch Hand
Posts: 518
A covariant return is when you override a method and make the return type of the method in the subclass different than the return type of the method in the superclass. The return type of the subclass' method must be a subclass of the return type of the superclass' method. In other words you can make the return type of the subclass' method the same or less general.

This wasn't allowed before Java 5.

Confused? Good. Here's an example:

Apple.getFoodSubstance() overrides the method Fruit.getFoodSubstance() and has a different return type -- a covariant return type. Apple.getFoodSubstance() returns an Apple which is a subclass of Fruit so the restriction is satisfied.

Kenny Johnson
Ranch Hand
Posts: 37
Thanks for the nice example. What does the word covariant mean though? Just wondering. The definitions on other sites are all very Math orientated.

Scott Johnson
Ranch Hand
Posts: 518
Merriam-Webster says:

covariant: varying with something else so as to preserve certain mathematical interrelations

In the case of Java covariants that could be:

covariant: varying with something else so as to preserve certain method interrelations

In other words, changing the return type while maintaining the rest of the method signature.

Ilja Preuss
author
Sheriff
Posts: 14112
Originally posted by Scott Johnson:

In other words, changing the return type while maintaining the rest of the method signature.

Not quite correct. It's the return type that is covariant, not the method itself. (Some languages also allow covariant argument types).

It simply means that the return type of an operation in a subtype may be more specific than the return type of the inherited operation.

Scott Johnson
Ranch Hand
Posts: 518
Not quite correct.

I stand corrected. Here's what Wikipedia has to say:

http://en.wikipedia.org/wiki/Covariance_and_contravariance_%28computer_science%29
[ January 02, 2007: Message edited by: Scott Johnson ]