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 ?
> 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.
> 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.