Christian Pflugradt wrote:You get a ClassCastException because Animal is not Dog but Dog is Animal. . . .
The compiler is programmed to enforce the Java® Language Specification (=JLS). It would be very difficult to predict the runtime type of the Animal object in K's line 7. Even harder like this:-It is programmed on the assumption that when the programmer promises to supply a Dog instance the will provide a Dog instance, not Cat or plain simple Animal. That is what you are doing when youChristian Pflugradt wrote: . . . The short answer is that the Java compiler can not detect all errors and those that are not detected will come up at Runtime. . . .I don't know the exact specifications, so if someone could point us to official documentation regarding which casting errors the compiler can detect I'd be grateful. . . .
Vishal Kurkure wrote:Thanks,Awesome explanation.
"Leadership is nature's way of removing morons from the productive flow" - Dogbert
Articles by Winston can be found here
Christian Pflugradt wrote: As far as casting is concerned the compiler will detect an attempt to cast to a completely unrelated object (like casting a Date to a String) but it won't detect incorrect downcasts.
I don't know the exact specifications, so if someone could point us to official documentation regarding which casting errors the compiler can detect I'd be grateful.
Campbell Ritchie wrote:Which compiler gave you that dead code warning?
Fred Kleinschmidt wrote:Here's a (contrived) case where the cast is proper:
this supposes, of course, that Kangaroo has a method hop() but Animal does not, and Whale has a method swim(), but Animal does not.
You're not going crazy. You're going sane in a crazy word. Find comfort in this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
|