given the following code, I have a question:
class A{}
class B extends A {}
class C extends B{}
public class Test {
public static void main(String[] args) {
Remember that legal casts are ruled by the "IS-A" test, why you can compile your code?, because ClassCastException
is an Unchecked Exception, since extends from RuntimeException
ClassCastException ---IS-A--> RuntimeException (Another example of a possible legal cast).
You are trying to cast a super class reference variable to a sub class type. You cannot do this. Think practical, a super class object cannot contain independent methods (other than the super class' methods) of the sub class.
At run-time you might call a method in the sub class which is certainly not in the super class object.
class A{
public void foo(){}
}
class B extends A {
public void bar(){}
}
Now,
A a=new A();
B b=(B)a;
b.bar();
When you call like this the compiler, will only check whether the method bar()
existed in the class B
. That's it. It doesn't care about what is in the 'object' because it is created at runtime.
But at runtime, as said before there is no bar()
method in the object a
. b
is just a reference that is pointing to object a but a
contains only foo()
not bar()
Hope you understood. Thank you.
In your code example, the variable a
is a reference to an object of type A.
The class B extends the class B,
but the relationship between classes A and B can only be described as follows:
This is legal: a = (A)b;
because class B isa class A.
One way to think of it is class B is a superset of class A.
If A is a set that contains (1, 2) and B is a set that contains (1, 2, 3) then B is a superset of A (in java terms: B can be cast to A) but A is not a superset of B (A can not be cast to B).
From a different point of view:
Socrates (class B) isa man (class A).
This is an invalid minor assertion: All men are Socrates.
Downcasts are illegal. An A is not a B and therefore you can't cast it to be one. You can cast B to be A, but not the other way round.
To downcast in Java, and avoid run-time exceptions, use the following code.
if (animal instanceof Dog) {
Dog dogObject = (Dog) animal;
}
Animal
is the parent class and Dog
is the child class.
All B's are A's, by inheritance. But not all A's are B's. This particular instance isn't, hence the runtime exception.