• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

ClassCast Exception

 
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi all,

i compiled the following code and it compiled but gave me a run time exception followed by the code



ERROR

Inside O
I am a Dog
Add Animal
Added Animal
Exception in thread "main" java.lang.ClassCastException
at o.main(o.java:29)

Questions
1) Why did it compile in the first place?
2) At runtime why Cast Exception, i am extending from Dog and casting o to it
3) if i change O = (o)dog to O = dog , it throws compile time error as follows :
found : Dog
required: o
O = dog;
^
1 error

Why so???
 
Ranch Hand
Posts: 234
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
(2)The variable dog is pointing to a Dog object and you want to cast this to an o object (horrible name by the way), but a Dog is not an o, therefore this is not possible and you get a ClassCastException.
(3)Same reason, a dog is not an o, therefore you can not just assign it to O.
(1)It compiles because it could have worked. When the dog variable would have been pointing to an o object, it would have been fine. (because an o is a Dog)

Try replacing the line

with

and see what happens.

You seem a little confused by the fact that an o is also a Dog, but a Dog is not an o.
[ September 27, 2007: Message edited by: bart zagers ]
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic