when ClassCastException occure?

hi everyone.

have the following code

class superC{

int i;

void add(int v){ i += v;}

void sub(int v){ i -= v;}

}

class subCextends superC{

void add(int v){ i += v*2;}

void mul(int v){ i *= v;}

}

class Testing{

publicstaticvoid main(String args[]){

subC down1 =new subC();

superC up1 = down1;

up1.add(1);// run add() from sub

System.out.println(up1.i);// output is 2

superC up2 =new superC();

subC down2 = (subC)up2;// line 18

down2.add(1);

System.out.println(down2.i);

}

}

if I compile it, no error, but when I ran it, I get :

2

Exception in thread "main" java.lang.ClassCastException

at Testing.main(Testing.java:18)

why did this exception occure ?

[1935 byte] By [Shawqi_Abbada] at [2007-10-2 3:18:23]
# 1
>why did this exception occure ?Because the actual object is a superC, not a subC. subC extends superC, and therefore may add functionality not present in a superC object. As such, a superC object cannot be cast to a subtype reference.Hope this helps...
yawmarka at 2007-7-15 21:45:51 > top of Java-index,Java Essentials,Java Programming...
# 2
it's an instance of superC but your trying it to cast it "subC". that's not valid; hence an error.this type of errror is only determinable at Runtime hence the reason you don't get the error at Compile Time.
prob.not.sola at 2007-7-15 21:45:51 > top of Java-index,Java Essentials,Java Programming...
# 3
thunx 4 your help,> and therefore may add functionality not present in a superC object.add() method presents in superC also
Shawqi_Abbada at 2007-7-15 21:45:51 > top of Java-index,Java Essentials,Java Programming...
# 4

> add() method presents in superC also

That doesn't matter. You cannot cast a supertype object to a subtype reference.

Review the part about how subtypes may add functionality. Say you modify the subC class to define a new method "foo()". What would you expect to happen if you called the foo() method on the subC reference that pointed to a superC object? Thankfully, the JVM disallows this condition by telling you that such a cast is impossible.

yawmarka at 2007-7-15 21:45:51 > top of Java-index,Java Essentials,Java Programming...
# 5

> Say you modify the subC class to

> define a new method "foo()". What would you expect to

> happen if you called the foo() method on the subC

> reference that pointed to a superC object?

> Thankfully, the JVM disallows this condition by

> telling you that such a cast is impossible.

I defined the following method in subC:

void foo(){};

and I insert the follwing fragement at the above code in particular at main():

subC f= (subC)up1;

f.foo();

and it was compiled and executed perfectly.

Shawqi_Abbada at 2007-7-15 21:45:51 > top of Java-index,Java Essentials,Java Programming...