wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes a test about casting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "a test about casting" Watch "a test about casting" New topic
Author

a test about casting

Domingo zhou
Greenhorn

Joined: Apr 14, 2004
Posts: 3

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

Joined: Jul 28, 2003
Posts: 1844

wawa is an interface...so we can assign a class reference ..
but it will give ClassCastException at run time...


Krishna Srinivasan
Spring Tutorials, OCAJP Mock Questions, 400+ OCPJP Mock Questions
Jeroen Wenting
Ranch Hand

Joined: Oct 12, 2000
Posts: 5093
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).


42
Satya Kondur
Greenhorn

Joined: Mar 19, 2004
Posts: 8
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

Joined: Dec 20, 2001
Posts: 3271
Psst.


SCJP Tipline, etc.
Domingo zhou
Greenhorn

Joined: Apr 14, 2004
Posts: 3
i got it.thanks everybody!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: a test about casting