Home > Java > javaTutorial > body text

Covariance, Invariance, and Contravariance: How Do Subtype Relationships Transform?

DDD
Release: 2024-11-12 06:07:01
Original
625 people have browsed it

Covariance, Invariance, and Contravariance: How Do Subtype Relationships Transform?

Understanding Covariance, Invariance, and Contravariance

Understanding the intricacies of covariance, invariance, and contravariance is crucial for mastering type relationships in programming.

What Are They?

In essence, these terms describe how the relationship between types and subtypes transforms. Let's consider a scenario where we have two types, A and B, and a transformation function f. Suppose ≤ denotes the subtype relation (with A ≤ B indicating that A is a subtype of B).

  • Covariant: f is covariant if A ≤ B implies f(A) ≤ f(B).
  • Contravariant: f is contravariant if A ≤ B implies f(B) ≤ f(A).
  • Invariant: f is invariant if neither of the above conditions holds.

Examples in Java

Let's explore some Java examples to clarify these concepts: