Member-only story
Understand Casting Generics in Java by Eating Broken Glass

You can feed anything you want to a black hole, but you shouldn’t feed broken glass to a human.
Typecasting in Java seems pretty straight forward: a Dog
is a type of Animal
, so anywhere you want anAnimal
, you can upcast aDog
to be an Animal
. Furthermore, if you have an Animal
that you actually know is a Dog
, then you can downcast that Animal
to be a Dog
.

Things get more complicated when you are dealing with generic types. If you have a Trainer<Dog>
, can you use it in place of a Trainer<Animal>
? What about in place of aTrainer<Schnauser>
?
In this post, we’ll develop a simple and intuitive metaphor that will help you understand casting of generics in Java, and how to solve some common use cases (as well as recognizing why certain common casting wants just won’t work).
The Metaphor
The image at the top of this article illustrates out metaphor. Put simply: you can feed anything you want to a black hole, but you can’t feed broken glass to a human.
The metaphor is made a bit more explicit in the following code, which will be explained below.