• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

ClassCastException

 
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 79
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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).]
reply
    Bookmark Topic Watch Topic
  • New Topic