• Post Reply Bookmark Topic Watch Topic
  • New Topic

ClassCastException  RSS feed

 
RajivAwadhesh kumar
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


why does the above java code not give error during compile time rather
than throw ClassCastException at run time?
 
John Jai
Rancher
Posts: 1776
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because String is a subclass of an Object and hence it's valid from casting from Object to String. And Object reference can refer to any of it's subclass instance polymorphically and the subclass being referred can be String too.

But when you try to cast between incompatible types you will get the compiler error.


Hence ClassCastException is a RuntimeException
 
Wendy L Gibbons
Bartender
Posts: 1111
Eclipse IDE Oracle VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the compiler doesn't try to work out the logic of your code, only that this is valid syntax, which it is.
 
Alex Armenteros
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
At line 6, x is an Object to the compiler not and Integer and casting is always allowed between classes and subclasses.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!