Home >Backend Development >C++ >Covariance and Contravariance in Programming: What's the Difference?
Easily understand covariance and contravariance
In object-oriented programming, covariance and contravariance describe the relationship between a base class and a derived class. They determine how a derived class is treated as its base class while ensuring type safety.
Covariance:
Covariance allows replacing primitive types in an API that are used only as outputs (e.g. return values) with "larger" (less specific) types. This means that a list of derived classes can be treated as a list of base classes. For example:
<code>List<水果> 水果列表 = new List<香蕉>(); // 协变</code>
Converse:
Contravariance allows replacing primitive types in an API that are used only as inputs (e.g., method parameters) with "smaller" (more specific) types. This means that parameters of base class types can be passed as parameters of derived class types. For example:
<code>基类 执行操作(派生类 变量); // 逆变</code>
Input/output terms:
In the context of generics, "in" and "out" are used to indicate whether the generic type is used as an input parameter or a return value.
Examples of interfaces and generics:
<code>// 输出 interface IMyInterface<out T> { T MyFunction(); } // 输入 interface IMyInterface<in T> { void MyFunction(T variable); }</code>
The above is the detailed content of Covariance and Contravariance in Programming: What's the Difference?. For more information, please follow other related articles on the PHP Chinese website!