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
- covariance and contravariance in mathematics and theoretical physics.
- polymorphism (computer science)
- inheritance (computer science)