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 you
Christian 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.
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.
Put the moon back where you found it! We need it for tides and poetry and stuff. Like this tiny ad:
ScroogeXHTML - small and flexible RTF to HTML converter libraryhttps://coderanch.com/t/710903/ScroogeXHTML-RTF-HTML-XHTML-converter