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

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

Nov 12, 2024 am 06:07 AM

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: