Co- and contravariance are means to add flexibility to the type system, ideally while making sure type safety cannot be violated. The flexibility part is clear: being able to treat an array of
apples as an array of
coconuts is more powerful than not being able to do so. But why is this example of array covariance unsafe? The true answer lies in the writable characteristic of an array:
// We're putting a Coconut, which is a Fruit, in a Fruit-array. This is// actually not fine if the underlying array has a more specific element type.fruits = new Coconut();
fruits variable is referencing an array with an element type that’s more specific than Fruit, the preceding code is not fine. The reason ...