File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

a test about casting

Domingo zhou

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.
Krishna Srinivasan
Ranch Hand

Joined: Jul 28, 2003
Posts: 1850

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

Krishna Srinivasan
OCAJP 7/8 Exam, 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).

Satya Kondur

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

SCJP Tipline, etc.
Domingo zhou

Joined: Apr 14, 2004
Posts: 3
i got it.thanks everybody!
I agree. Here's the link:
subject: a test about casting
jQuery in Action, 3rd edition