As used in computer science, in particular in object oriented programming:
- Covariance means that the type of arguments, return values, or exceptions of overriding methods can be subtypes of the original types.
- Contravariance means that the type of arguments, return values, or exceptions of overriding methods can be supertypes of the original types.
This is contrasted with invariance, where arguments have to be of exactly the same type.
As is usual in the case of object oriented programming, type can be a class and supertype can be any superclass or any implemented protocol or interface.
Covariant parameters are not safe, but covariant return types and exceptions are. Similarly, contravariant parameters are safe, but contravariant return types and exceptions 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 values and exceptions than expected.
The issue is somewhat implicit in object-oriented design and programming in general, but becomes explicit in generic programming, for example.
Language support
C++
C++ supports covariant return types in overridden virtual functions.
C#
In the C# programming language, support for both return-type covariance and parameter contravariance for delegates was added in version 2.0 of the language. This could result in a lack of source-compatibility with code written for earlier versions of the language, but only in somewhat contrived examples.
Neither covariance nor contravariance are supported for method overrriding.
Eiffel
In Eiffel you can get compiler errors, because polymorphism breaks.
Java
Exception covariance has been supported since the introduction of the language. Return type covariance is implemented in the Java programming language version J2SE 5.0. Parameter types have to be exactly the same (invariant) for method overriding, otherwise the method is overloaded with a parallel definition instead.
REALbasic
REALbasic added support for return type covariance in version 5.5. As with Java, the parameter types of the overriding method must be the same.
Scala
Scala supports both covariance and contravariance.
Sather
So does Sather.
See also
- covariance and contravariance in mathematics and theoretical physics.
- polymorphism (computer science)
- inheritance (computer science)
External links
- http://c2.com/cgi/wiki?ContraVsCoVariance (note this article is not updated about C++)