Generics and Variance with Java
dev.to·12h·
Discuss: DEV

In this article, we’ll learn about generics in Java, with an emphasis on the concept of variance.

Substitution of Values

Let’s start by introducing types and subtypes. Java supports assigning a subclass value to a variable of a base type. This is known as a widening reference assignment. We can therefore say that a Float is a subtype of a Number:

Float myFloat = Float.valueOf(3.14f);
Number number = myFloat;

Arrays are covariant and reified

Variance tells us what happens to this subtyping relationship when the original types are placed in the context of another type.

Let’s take arrays, for example. We can ask, since Float is a subtype of a Number, what can we say about an array of Floats relative to an array of Numbers?

It turns out that in Java, arrays are c…

Similar Posts

Loading similar posts...