wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Problem with 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 "Problem with casting" Watch "Problem with casting" New topic
Author

Problem with casting

Federico Er
Greenhorn

Joined: Jun 22, 2010
Posts: 8
Hi there,

i'm training for the SCJP exam and i just can't get something out of my mind, two pieces of code from the second chapter's Self Test



And the other one is



It must be really silly, but i don't understand why the first one causes a compile error in line 15 while the second one an exception at runtime.

Thanks in advance
Tom Reilly
Rancher

Joined: Jun 01, 2010
Posts: 618
What is the compiler error? What is the runtime error?
Federico Er
Greenhorn

Joined: Jun 22, 2010
Posts: 8
Thanks for answering!

In the DogShow example is a compiler error in line 17, sorry, not 15:



But in the Redwoodone it compiles just fine and i get an Exception at Runtime


I don't understand why in DogShow i'm stoped by the compiler instead of recivieng later a ClassCastException
Tom Reilly
Rancher

Joined: Jun 01, 2010
Posts: 618
1. You are casting Hound to a Dog. Dog does not have a sniff() method. The compiler at this point only knows about Dog so it complains.
2. A Redwood IS A Tree. But a Tree IS NOT A Redwood. You are telling the compiler that a Tree is a Redwood so it believes you. The JVM knows you are lying.
Federico Er
Greenhorn

Joined: Jun 22, 2010
Posts: 8
Oh i see,

i get the compiler error when javac notices that there is no sniff() method on Dog. On the other hand, i get a ClassCastException when the casting itself is wrong...

Thanks alot, really, for the fast answer!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Problem with casting
 
Similar Threads
Reference Variable casting ... compile Errors vs Runtime errors
Please clarify my understanding of Polymorphism
Casting
A doubt in the type casting
Confusion in Polymorhphism Self test questions K&B Book