• Post Reply Bookmark Topic Watch Topic
  • New Topic

classCastException  RSS feed

 
jnrohit Jain
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

When I cast a class into an unrelated class then it gives me a compile time error (incompatible types) and when I cast a class into an unrelated interface it gives me a runtime exception (classCastException). Why casting to interface not giving compile time error?

 
Campbell Ritchie
Marshal
Posts: 56598
172
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because it is possible to create a subtype of that black ink class which does implement that interface. The compiler cannot therefore say the cast can never succeed, so it has to permit it.
Remember that casts usually signify a bad inheritance structure, and also that the javac tool is programmed to believe that users know what they are doing with casts.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!