Another way to ask the same question is, given 2 classes A and B, is it synonymous to say: "Object A can be cast into B" and "Object A is a descendant of B"?
Thanks,
JDelage
Edit: Clarified the question to make it clearer 开发者_高级运维that both A and B are classes.
"Java - Can you cast an object into a class it doesn't extend?" - No, you can't.
"Basically, is it synonymous to say: "Object A can be cast into B" and "Object A is a direct descendant of B"?" - Yes. Plus in the case when A is of a class implementing interface B.
No, you can't. It throws a ClassCastException.
If it is not direct descendant or not the implementation of interface
class A;
class B extends A;
A a = new B();
interface A;
class B implements A;
(A) B
In other situation
It will throw ClassCastException http://download.oracle.com/javase/1.4.2/docs/api/java/lang/ClassCastException.html
Yes you can, if B is interface and A is implementation of B
Suppose you have:
interface I {}
class A implements I {}
class B extends A {}
class C extends B {}
all of the following are valid:
(I)C;
(A)C;
(B)C;
精彩评论