• Post Reply Bookmark Topic Watch Topic
  • New Topic

ClassCastException Exception  RSS feed

 
Smita Chopra
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The following program gives a ClassCastException at runtime


Can you please tell me why doesn't it give an error at compile time when its very clear that assigning Object to String is going to fail.
 
Steve Morrow
Ranch Hand
Posts: 657
Clojure Spring VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It may be clear to you, but the compiler doesn't have any way of knowing for certain that such a cast won't work. The example posted is trivial; quite often, a particular implementation is unknown at compile-time, so the compiler trusts you know what you're doing when you cast a reference.
 
Anil Chandran
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Only at runtime it can be made sure that the object cant be casted to a string .

Object is a super class of String . So casting an object to string cant cause a compile time error.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!