Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

a test about casting

 
Domingo zhou
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Why the code "pogo = (SwampThing)wawa;" will cause runtime exception but not a complile time error.
I think,the "wawa" is Washer type thich is not relevant to the
hierarchy from "animal" to "Swampthing".So the explicit casting will cause
complile error.But im am wrong.
Why???
 
Krishna Srinivasan
Ranch Hand
Posts: 1874
Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
wawa is an interface...so we can assign a class reference ..
but it will give ClassCastException at run time...
 
Jeroen Wenting
Ranch Hand
Posts: 5093
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
More descriptive: a subclass of SwampThing might implement Washer so a cast to SwampThing of a Washer might be valid if the Washer being cast is a SwampThing, which cannot be detected at compiletime (though in this simple case the compiler could find it maybe, it's not designed to do so).
 
Satya Kondur
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
JLS Quote:
"If S is a class type: ... If T is an interface type: ... If S is not a final class (�8.1.1), then the cast is always correct at compile time (because even if S does not implement T, a subclass of S might).
If Swampthing were to be a final class it would resu,t in a compile time error.
 
Corey McGlone
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Psst.
 
Domingo zhou
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i got it.thanks everybody!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic