aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes ClassCastException 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 "ClassCastException" Watch "ClassCastException" New topic
Author

ClassCastException

manila naik
Greenhorn

Joined: Aug 01, 2000
Posts: 10
Hello,
can anyone help me in the following code ?
class Test{
void show(){
System.out.println("Test class");
}
}
class Q extends Test{
void show(){
System.out.println("Q class");
}
public static void main(String args[]){
Test t = new Test();
Q q = new Q();
t.show();
q.show();

/*1:*/ t = q;
/*2: */ t.show();
q = (Q) t; // compile and run
// (ie ClassCastException is not generated)
t.show();

}
}
but if line 1 and 2 are commented,it gives runtime exception as
ClassCastException evevn though i think casting is properly,
can anyone help me ?
thanks in advance
manila
thomas
Ranch Hand

Joined: May 26, 2002
Posts: 79
manila:
if line 1 is commented out, the variable t will continue to refer to an instance of class Test (super class). Then you CANNOT assign it to a variable of type Q (subclass) either with or without a cast.
On the other hand, you can assign an instance of sub class to a variable of the super class type.
[This message has been edited by thomas (edited August 16, 2000).]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: ClassCastException