Understanding Covariance, Invariance, and Contravariance in Plain English
Covariance, invariance, and contravariance are terms that describe how typing relationships behave under certain transformations. In programming, these transformations can be type conversions, method overriding, or inheritance.
Covariance
Covariance means that a subtype of a type will also be a subtype of the transformed type. For example, if class A is a subtype of class B, and we have a function f(T) that takes a type T and returns a transformed type T'', then if A is a subtype of B, f(A) will also be a subtype of f(B).
Contravariance
Contravariance is the opposite of covariance. In contravariance, a subtype of a type will map to a supertype of the transformed type. If the same function f(T) from the covariance example above were contravariant, then if A is a subtype of B, f(B) would be a subtype of f(A).
Invariance
Invariance means that neither covariance nor contravariance applies to the transformation. That is, the subtype relationship is unaffected by the transformation.
Examples
Consider the following examples:
Java Generics
Generics in Java are invariant. This means that List
Arrays
Arrays in Java are covariant. This means that String[] is a subtype of Object[].
Method Overriding
In method overriding, covariance applies to return types and contravariance applies to parameter types. That is, if a subclass overrides a method of the superclass, the return type can be covariant (a subtype of the superclass method's return type) and the parameter types can be contravariant (supertypes of the superclass method's parameter types).
In conclusion, covariance, invariance, and contravariance describe how typing relationships behave under different transformations, such as type conversions, method overriding, or inheritance. Understanding these concepts can help programmers write more flexible and extensible code.
The above is the detailed content of What are Covariance, Invariance, and Contravariance in Plain English?. For more information, please follow other related articles on the PHP Chinese website!