Home  >  Article  >  Java  >  Covariance, Invariance, and Contravariance in Java: What's the Difference and Why Should I Care?

Covariance, Invariance, and Contravariance in Java: What's the Difference and Why Should I Care?

Susan Sarandon
Susan SarandonOriginal
2024-11-12 01:38:02268browse

Covariance, Invariance, and Contravariance in Java: What's the Difference and Why Should I Care?

Covariance, Invariance, and Contravariance Explained in Plain English

Introduction:
Understanding covariance, invariance, and contravariance can be challenging, but it's essential for comprehending type transformations and relationships in Java. This article aims to simplify these concepts and provide real-world examples to enhance understanding.

Covariance:
Covariance describes a type transformation where the subtype relation is preserved. If type A is a subtype of type B, then the transformation f(A) will result in f(B) being a subtype of f(A).

Example:
Consider a transformation f(List) = List. Since List is a supertype of List, then List> is a supertype of List>. This demonstrates covariance.

Invariance:
Invariance occurs when the subtype relation is not affected by type transformations. If A is a subtype of B, then f(A) will not be a subtype or supertype of f(B).

Example:
Java generics behave in an invariant manner. For example, f(ArrayList
) = ArrayList. Since ArrayList and ArrayList are different types, neither is a subtype or supertype of the other.

Contravariance:
Contravariance is the inverse of covariance. The subtype relation is reversed during transformations. If A is a subtype of B, then f(B) will be a subtype of f(A).

Example:
Consider the type transformation f(A[]) = B[]. In Java, arrays are covariant, which means that if A[] is a subtype of B[], then f(A[]) = B[] will also be a subtype of f(B[]) = B[].

Applications:
Covariance, invariance, and contravariance play crucial roles in Java:

  • Assignment: Only objects of compatible types can be assigned to each other. The compiler checks if the source type is a subtype of the target type.
  • Method Invocation: When invoking a method, the actual parameters must be a subtype of the declared parameter types. The method's return type must be a supertype of the expected return type.
  • Overriding: In Java, the parameter and return types of overridden methods must match or covary with the original method's types.

The above is the detailed content of Covariance, Invariance, and Contravariance in Java: What's the Difference and Why Should I Care?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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