Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Problem with casting

 
Federico Er
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 618
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is the compiler error? What is the runtime error?
 
Federico Er
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 618
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic