Home > Java > javaTutorial > What are Covariance, Contravariance, and Invariance in Java, and How Do They Affect Type Transformations?

What are Covariance, Contravariance, and Invariance in Java, and How Do They Affect Type Transformations?

Patricia Arquette
Release: 2024-11-09 15:04:02
Original
687 people have browsed it

What are Covariance, Contravariance, and Invariance in Java, and How Do They Affect Type Transformations?

Understanding Covariance, Contravariance, and Invariance in Java Simplified

Introduction

Covariance, contravariance, and invariance are fundamental concepts in object-oriented programming, particularly in Java. They define how the relationship between types and subtypes is affected by type transformations.

Covariance, Contravariance, and Invariance Defined

In the context of type transformations, covariance, contravariance, and invariance determine whether the subtype relation is preserved. Let's consider a type transformation f that takes a type A and transforms it into a type f(A). If:

  • Covariant: For types A and B such that A ≤ B (A is a subtype of B), f(A) ≤ f(B).
  • Contravariant: For types A and B such that A ≤ B, f(B) ≤ f(A).
  • Invariant: Neither covariance nor contravariance applies.

Examples in Java

Let's consider some examples in Java: