File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes casting problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "casting problem" Watch "casting problem" New topic

casting problem

payal sharma
Ranch Hand

Joined: Oct 04, 2000
Posts: 57

C:\JAVA>java Test
java.lang.ClassCastException: Base
java.lang.ClassCastException: Base
Here I am unable to understand the output the class cast exception with
Base two times and then true why?
Please explain this.
thanks in advance
[This message has been edited by payal sharma (edited July 27, 2001).]
Mikael Jonasson
Ranch Hand

Joined: May 16, 2001
Posts: 158
The two exceptions for base are:
Cloneable c1=(Cloneable)x;
Cloneable c2=(Cloneable)x;
When called with base. Since all objects extends Object, Test will always print "true" when called with an object (both base and child are objects). Since base implements runnable and child extends base, the cast to runnable will work for both. Child implenets colneable, so the above cast will work for it.
Dow this explain it?
Desai Sandeep
Ranch Hand

Joined: Apr 02, 2001
Posts: 1157
The Base class doesnot implement Cloneable.Hence you cannot cast its instance to Cloneable.You get the two exceptions for statements :

Cloneable c1=(Cloneable)x;
Cloneable c2=(Cloneable)x;

when x is an instance of Base class.
When x is a instance of Child class, the above statements would not give ClassCastException , since Child class implements Cloneable.
When either of the constructors are invoked, each being an instanceof the Object prints true in the output.
Hope this helps,
SCJP2, OCSD(Oracle JDeveloper), OCED(Oracle Internet Platform)
I agree. Here's the link:
subject: casting problem
It's not a secret anymore!