• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
Bartenders:
  • Piet Souris
  • Himai Minh

Problem with casting

 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Rancher
Posts: 618
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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!
 
it's a teeny, tiny, wafer thin ad:
free, earth-friendly heat - a kickstarter for putting coin in your pocket while saving the earth
https://coderanch.com/t/751654/free-earth-friendly-heat-kickstarter
reply
    Bookmark Topic Watch Topic
  • New Topic