Home > Backend Development > C++ > What is the Difference Between Covariance and Contravariance in Object-Oriented Programming?

What is the Difference Between Covariance and Contravariance in Object-Oriented Programming?

Linda Hamilton
Release: 2025-01-20 17:12:10
Original
856 people have browsed it

What is the Difference Between Covariance and Contravariance in Object-Oriented Programming?

In-depth understanding of covariance and contravariance

Covariance and contravariance in object-oriented programming allow replacement of different types in different situations while maintaining type safety.

Covariance

Covariance applies when a "supertype" (more general) is used as a substitute for a "subtype" (more specific) in the output position (e.g., as a return value). In this case, you can assign a list of supertype to a list of subtype:

<code class="language-java">List<Fruit> fruits = new ArrayList<>();
List<Apple> apples = fruits; // 协变:List<Apple> 是 List<Fruit> 的子类型</code>
Copy after login

Contravariance

Contravariance applies when a "subtype" is used as a replacement for a "supertype" at the input position (for example, as a method parameter). In this case, you can pass a lambda expression that accepts a subtype to a lambda expression that expects a supertype:

<code class="language-java">Comparator<Apple> compareApples = (a, b) -> a.compareTo(b);
Comparator<Fruit> compareFruits = compareApples; // 逆变:Comparator<Apple> 是 Comparator<Fruit> 的子类型</code>
Copy after login

“in” and “out” keywords

The "in" and "out" keywords in generics are used to specify the variance of generic parameters. "out" means covariance, "in" means contravariance.

In the example of the MyInterface interface:

  • Covariance (return value):
<code class="language-java">interface MyInterface<out T> {
    T get(); // T 可以是 T 的原始类型的任何子类型
}</code>
Copy after login
  • Inversion (input parameters):
<code class="language-java">interface MyInterface<in T> {
    void set(T value); // T 必须是 T 的原始类型的子类型
}</code>
Copy after login

In summary, covariance and contravariance allow safe type substitution based on the intended use of the generic type, ensuring type safety while providing code design flexibility.

The above is the detailed content of What is the Difference Between Covariance and Contravariance in Object-Oriented Programming?. 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