• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

ClassCastException on downcasting

 
shivang sarawagi
Ranch Hand
Posts: 157
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When I run the below program, I get a runtime classcast exception
that you cannot downcast Tree into Scratch.
I don't understand why. Can anyone help me out. Thanks

 
Mansukhdeep Thind
Ranch Hand
Posts: 1158
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is the relationship between the two entities? Can you tell me?
 
shivang sarawagi
Ranch Hand
Posts: 157
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I got the solution

Downcasting is possible only when a variable of the base class (parent class) has a value of the derived class (child class).

 
Mansukhdeep Thind
Ranch Hand
Posts: 1158
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes. A simple way to check if reference variable casting will work is to use the instanceof test.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic