Covariance vs. contravariance with respect to class inheritance

后端 未结 4 2207
猫巷女王i
猫巷女王i 2021-02-09 14:00

What is the meaning of the concepts \'covariance\' and \'contravariance\'?

Given 2 classes, Animal and Elephant (which inherits from

4条回答
  •  鱼传尺愫
    2021-02-09 14:29

    You have it backwards. You can add an Elephant to an Animal array because it is an Animal, and it's guaranteed to have all of the methods an Animal is required to have. You can't add an Animal to an Elephant array because it does not have all of the methods that an Elephant is required to have.

    The Wikipedia article on covariance and contravariance has a good explanation of this:

    Within the type system of a programming language, an operator from types to types is covariant if it preserves the ordering, ≤, of types, which orders types from more specific ones to more generic ones; it is contravariant if it reverses this ordering. If neither of these apply, the operator is invariant. These terms come from category theory.

    Also, you said that type Elephant was "bigger", and this is not the case. Type Animal is "bigger" in the sense that it includes more specific types, such as Elephant, Giraffe, and Lion.

提交回复
热议问题