• Post Reply Bookmark Topic Watch Topic
  • New Topic

Difficulty of understanding ClassCastException  RSS feed

 
Soner Abdulzahir Al-Alimi
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I can't comprehend why the following casts(1 and 2) aren't allowed. Can you explain me in a way that I can envision? As far as I research, it is said that an object of a base class can’t be cast to an object of its derived class. If it is right, why the instanceof operator in use? I examined some examples trying to explain using animals etc. but I can't get really why.

 
Viktor Logwin
Ranch Hand
Posts: 99
15
Chrome Java Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
An Author is a subclass of a Programmer.

A cast tells compiler something like "Hey, I know what I am doing, so let a Programmer be an Author". And compiler says "Yes, Master!". But on runtime there is a ClassCastException, because you didn't hear to your compiler.
This is what happens on both commented lines of code.

You create a new Programmer-object and you try to cast it to an Author. But the object actually created is the Programmer object. In Java if you create a hierarchy, you can say "an Author is-a Programmer" because it extends the Programmer class. But not vice versa. So Programmer is not an Author.

This line would be ok:

Even without a cast. Besause compiler knows, that an Author is a Programmer.

An Author and a Programmer is maybe not the best example. Let's take an Animal, a Moose and a Cow. You can say "a Cow is an Animal" or "a Moose is an Animal", but not "an Animal is a Cow" or "an Animal is a Moose". Just think about a hierarchy when you see casts and reference types in Java.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!