• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why do we get a ClassCast Exception in below code?  RSS feed

 
radha gogia
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


I am unable to get the reason for it.
 
Ivan Jozsef Balazs
Rancher
Posts: 999
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Every Redwood is a Tree, but not every Tree is a Redwood.
An object created with "new Tree()" is a (plain, that is, no Redwood) tree.
Method go2 assumes the Tree t1 argument is a Redwood, which it is not.
 
Guillermo Ishi
Ranch Hand
Posts: 789
C++ Linux Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In case you aren't used to casts in Java. In some languages a cast changes the thing being cast. But in Java, in regard to instances, it only tells the compiler the instance will be of a certain type at runtime so it will compile. It if tuns out that you lied to the compiler, then you'll get the error you got.
 
Stevens Miller
Bartender
Posts: 1445
30
C++ Java Netbeans IDE Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please UseCodeTags, radha. I added them and reformatted your code, slightly.
 
radha gogia
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But here Tree is a super class and the argument Tree t1 its is accepting the value (Redwood)new Tree ,therefore ,the superclass refernce variable is refereing to its child class reference instance as it is type-casted to it ,so then what is the problem here?
 
Ivan Jozsef Balazs
Rancher
Posts: 999
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In line #8 you call go2


that is, with a new Tree() as t1 and go2 assumes its t1 argument is a Redwood which it is not.
If t1 = new Tree() then the cast (Redwood)t1 fails.
 
Ivan Jozsef Balazs
Rancher
Posts: 999
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A stack trace shows you where the error occurred - it is often a valuable help.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!