Covariance and contravariance (computer science) |
As used in computer science, in particular in object oriented programming:
*Covariance means that arguments or return value of virtual 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 Comparison of generics to templates, for example.
=Language support=
==Eiffel==
In Eiffel programming language you can get Compiler errors, because polymorphism (computer science) breaks.
==Java==
Return type covariance is implemented in the Java programming language programming language.
=See also=
*covariance and contravariance in mathematics and theoretical physics. *polymorphism (computer science) *inheritance (computer science)
=External links=
*http://c2.com/cgi/wikiContraVsCoVariance|
|