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>
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>
“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:
<code class="language-java">interface MyInterface<out T> { T get(); // T 可以是 T 的原始类型的任何子类型 }</code>
<code class="language-java">interface MyInterface<in T> { void set(T value); // T 必须是 T 的原始类型的子类型 }</code>
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!