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

Why ClassCastException at run time

chi Lin
Ranch Hand

Joined: Aug 24, 2001
Posts: 348
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));

}
}


not so smart guy still curious to learn new stuff every now and then
Roy Ben Ami
Ranch Hand

Joined: Jan 13, 2002
Posts: 732
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

Joined: Dec 20, 2001
Posts: 3271
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 ]

SCJP Tipline, etc.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Why ClassCastException at run time