*
The moose likes Beginning Java and the fly likes ClassCastException on downcasting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "ClassCastException on downcasting" Watch "ClassCastException on downcasting" New topic
Author

ClassCastException on downcasting

shivang sarawagi
Ranch Hand

Joined: Jun 19, 2008
Posts: 147
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

Joined: Jul 27, 2010
Posts: 1157

What is the relationship between the two entities? Can you tell me?


~ Mansukh
shivang sarawagi
Ranch Hand

Joined: Jun 19, 2008
Posts: 147
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

Joined: Jul 27, 2010
Posts: 1157

Yes. A simple way to check if reference variable casting will work is to use the instanceof test.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: ClassCastException on downcasting