Forums Register Login

a test about casting

+Pie Number of slices to send: Send

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???
+Pie Number of slices to send: Send
wawa is an interface...so we can assign a class reference ..
but it will give ClassCastException at run time...
+Pie Number of slices to send: Send
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).
+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
+Pie Number of slices to send: Send
i got it.thanks everybody!
Evil is afoot. But this tiny ad is just an ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 561 times.
Similar Threads
a test about casting
casting with Interface
Class Cast Error
Cast doubt
Cast
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 13:18:44.