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
Eiffel
In Eiffel you can get compiler errors, because polymorphism breaks.
Java
Return type and exception 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.
See also
- covariance and contravariance in mathematics and theoretical physics.
- polymorphism (computer science)
- inheritance (computer science)