Covariance and contravariance (computer science)

This is an old revision of this page, as edited by TuukkaH (talk | contribs) at 05:57, 30 November 2005 (Java: extend). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

As used in computer science, in particular in object oriented programming:

  • Covariance means that arguments or return value of overriding methods can be of subtypes of the original types.
  • Contravariance means that arguments or return value of overriding methods can be of supertypes of the original types.

This is contrasted with invariance, where arguments have to be of exactly the same type.

Covariant parameters are not safe, but covariant return types are. Similarily, contravariant parameters are safe, but contravariant return types are not. This is because the caller may expect the original type, but in subtyping it doesn't matter if the overriding method cares less about parameters and cares more about return value than expected.

The issue is somewhat implicit in object-oriented design and programming in general, but becomes explicit in Java generics, for example.

Language support

Eiffel

In Eiffel you can get compiler errors, because polymorphism breaks.

Java

Return type covariance is implemented in the Java programming language version 1.5. Parameter types have to be exactly the same (invariant) for method overriding, otherwise the method is overloaded with a parallel definition instead.

See also