• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why will this throw Class Cast Exception?

 
Alan Blass
Ranch Hand
Posts: 161
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi! I have:



Can't a1 downcast to class B on line 14?
 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Alan Blass wrote:Can't a1 downcast to class B on line 14?

a1 is referring to an array of type A (with a size of 10). What makes you think you could cast it to an array of type B?

Let's assume that A stands for Animal and B stands for Bird (a subclass of Animal). So you have an array with Animals (which can contain Birds... and also Cats, Dogs, Lions,...) and you want to turn it into an array of Birds. But not every Animal is a Bird! That's why you get a ClassCastException.
 
Alan Blass
Ranch Hand
Posts: 161
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi!

Thanks for your answer.

I thought I could cast down any superclass to a subclass just by inserting an explicit cast.

Only the following casts are valid.



Correct me if I am wrong. Thanks.
 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Likes 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Alan Blass wrote:I thought I could cast down any superclass to a subclass just by inserting an explicit cast.

You definitely can! You won't get any compiler errors, but you can get a ClassCastException if the actual object doesn't pass the IS-A test with the type of the cast.

A little code example to illustrate:


So the 1st explicit cast compiles and doesn't throw a runtime exception, because reference variable a1 refers to a Cat object and you want to cast to Cat. Cat IS-A Cat, so no problem here. The 2nd explicit cast compiles but at runtime you'll get a runtime exception, because reference variable a2 refers to a Dog object and you want to cast to Cat. Cat IS-NOT-A Dog, so you'll get a ClassCastException at runtime.

Hope it helps!
Kind regards,
Roel
 
Alan Blass
Ranch Hand
Posts: 161
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok. This made it clear. Thanks.
 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nice to know: instead of making a "thank you" post, you could also the post(s) which you liked. It's easier, faster and other ranchers will see immediately which are the "starred" posts.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic