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 Why ClassCastException at run time Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Why ClassCastException at run time" Watch "Why ClassCastException at run time" New topic

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)
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();


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.
[ May 20, 2002: Message edited by: Corey McGlone ]

SCJP Tipline, etc.
I agree. Here's the link:
subject: Why ClassCastException at run time
It's not a secret anymore!