Reputation: 15
I'm aware that this could be a possible duplicate, but the other threads haven't solved my problem completely.
Let's say I have the following classes A and B which extend BasicClass.
public abstract class BasicClass {
// ...
}
public class A extends BasicClass {
// ...
}
public class B extends BasicClass {
// ...
}
And now I want to cast class A to B dynamically.
a.getClass().cast(bClass.newInstance);
but every time I get an Exception.
java.lang.ClassCastException
at java.lang.Class.cast(Unknown Source)
Can you tell me why?
Upvotes: 0
Views: 192
Reputation: 26
Because A is not extending B. (technicaly: A IS not B)
JVM performs "IS-A" test before it casts. If "IS-A" test fails, you will get "ClassCastException".(Just like you are getting now).
IS-A : IS-A test is to check whether a class(to be casted, in your case A) is in inheritance tree of the class(casted to, in your case B).
IS-A is the functional term, syntax to check IS-A test is instanceof".
e.g a instanceof b :
explanation of instance of:
LHS and RHS of the instance of must be the object.
thus a and b are obeject.
Their respective classes are checked for inheritance.
a instanceof b : False
a instanceof basicObject : True
b instanceof a : False
b instanceof basicObject : True
basicObject instanceof a : False
basicObject instanceof b : False
You can only cast where result of instanceof is true.
Upvotes: 1
Reputation: 12558
Your hierarchy looks like this:
BasicClass
/ \
/ \
A B
A
is not an ancestor of B
, so it's impossible to cast an instance of B
to A
.
Upvotes: 0
Reputation: 279960
Because, in your inheritance hierarchy, a B
is not an A
. You cannot cast one to the other.
Upvotes: 4