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 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


manila naik

Joined: Aug 01, 2000
Posts: 10
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();;;

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

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
Ranch Hand

Joined: May 26, 2002
Posts: 79
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:
subject: ClassCastException
It's not a secret anymore!