File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Problem with ClassCastException Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Problem with ClassCastException" Watch "Problem with ClassCastException" New topic

Problem with ClassCastException

Sudhanshu Gupta

Joined: May 02, 2009
Posts: 23
hi all,
I was taking the self test in SCJP study guide where this code confused me.

This code throws ClassCastException when Tree is downcast to Redwood.
But I dont understand why. To try this out I used an existing code and tried upcasting and downcasting.
I dont understand how come this one is working fine.


Sudhanshu Gupta

Thanks & Regards

Sudhanshu Gupta

Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24195

Sorry to say, my friend, but you are mistaken; your example is not working fine. It will compile, yes, but at runtime, the line

NewTest n = (NewTest)t1; //throws no exception

absolutely will throw a ClassCastException. A cast can never actually change an object; it can only tell the compiler something that is true. So the first cast, from a NewTest object to class Test, is OK, because a NewTest is-a Test. But the second cast fails, since the object is really an instance of Test, and can't be converted to NewTet. There's a third thing you can do which does work, and I think that's the interesting case that you're missing:

Test t2 = new NewTest();
NewTest t3 = (NewTest) t2;

You can't make the second assignment without the cast, but with the cast, it's legal, since t2 really does hold a NewTest instance.

[Jess in Action][AskingGoodQuestions]
Sudhanshu Gupta

Joined: May 02, 2009
Posts: 23
hi Ernest Friedman-Hill
thank you very much for clearing my confusion.
Actually I was thinking of collections which return Object instances that can be cast to other types.
The third thing you told about clarified everything.
thank you once again.


Sudhanshu Gupta
wood burning stoves
subject: Problem with ClassCastException
It's not a secret anymore!