开发者

Java - Can you cast an object into a class it doesn't extend?

开发者 https://www.devze.com 2023-01-30 16:52 出处:网络
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\"?

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;
0

精彩评论

暂无评论...
验证码 换一张
取 消