The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +772K…

Follow publication

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.

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

The Startup
The Startup

Published in The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +772K followers.

Brian Mearns
Brian Mearns

Written by Brian Mearns

Software Engineer since 2007 ・ Parent ・ Mediocre Runner ・ Flower and Tree Enthusiast ・ Crappy Wood Worker ・ he/him or they/them

Responses (2)

Write a response