Home > Java > javaTutorial > body text

What are Covariance, Invariance, and Contravariance in Plain English?

Mary-Kate Olsen
Release: 2024-11-11 01:51:03
Original
980 people have browsed it

What are Covariance, Invariance, and Contravariance in Plain English?

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, for example, is neither a subtype nor a supertype of 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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template