Brian Mearns
1 min readJul 26, 2021

Your syntax is a little unclear, but I think I get the gist of what you're asking.

In your first example, I'm assuming "obj" is typed as Object. If that's the case, you're casting is telling the compiler that you know it is specifically of type E. Since Object is the super-type of everything, I believe this is possible and the compiler will let you do it, but you are risking a ClassCastException at runtime if you're wrong.

It's conceptually similar in the second example, but I think it depends on whether or not the compiler can determine that E is a subtype of A. I assume this is meant to read as "E element = (E) a" where "a" is of type "A".

I'm assuming the last example is supposed to be "Object obj = (Object) e", where "e" is of type "E". This you can always do because Object is a super-type of every other type. In this case, the cast expression isn't even necessary because the compiler already knows that every value is an Object.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

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

No responses yet

Write a response