Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why ClassCastException at run time

 
chi Lin
Ranch Hand
Posts: 348
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Could someone explain why the following code cause a ClassCastException when I tries to run it
(it compiles OK)
thanks
class Parent {

int i = 5;

}
class Child extends Parent {
int i = 15;
int getvalue(Child c) {
return c.i;
}
}
class TestCast {
public static void main (String args[]) {
Parent p = new Parent();
Child c = new Child();
System.out.println(c.getvalue((Child)p));

}
}
 
Roy Ben Ami
Ranch Hand
Posts: 732
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
because the p is a Parent! its not a child at all. you can convert a Parent to a Child!
every Child is a Parent but not the other way around.
if u did:
Parent p=new Child();
then it would work.
because then the p would actually refrer to a Child and not to a parent.
get it?
 
Corey McGlone
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Remember this:
"You can use a child wherever a parent is expected."
Note that this only goes one way. You can't use a parent where a child is expected. But, if you can remember this, you'll be fine.
Corey
[ May 20, 2002: Message edited by: Corey McGlone ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic