File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

ClassCastException

 
manila naik
Greenhorn
Posts: 10
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 79
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic