Sobes.tech
Middle+

What is type covariance?

sobes.tech AI

Answer from AI

Covariance of types is a property of type systems where a more specific (subtype) type can be used in places where a more general (supertype) type is expected.

In the context of Java, this often manifests when working with inheritance and generics. For example, if class Cat inherits from Animal, covariance allows using Cat where Animal is expected.

However, in Java, generics are invariant by default, meaning List<Cat> is not a subtype of List<Animal>. To support covariance, wildcard types with ? extends are used:

List<? extends Animal> animals = new ArrayList<Cat>();

Here, ? extends Animal indicates that the list contains objects of type Animal or its subtypes, allowing safe reading of objects from the list but preventing adding new elements (except null).

Thus, covariance helps in using subtypes where more general types are expected, maintaining type safety and code flexibility.

What is type covariance? — Java - sobes.tech