[英]Casting in Java(interface and class)
if: 如果:
interface I{}
class A implements I{}
class B extends A{}
class C extends B{}
A a = new A();
B b = new B();
Why a = (B)(I)b; is correct
but b = (B)(I)a; is false?
I find casting to be very confusing, what is the best way to understand if I can down cast or up cast an object? 我发现施法很混乱,如果我可以向下施放或向上施放物体,最好的方法是什么?
Your class hierarchy looks like this: 您的类层次结构如下所示:
Object x
can be casted to class Y
, if runtime type of x
is subclass of Y
. 如果
x
运行时类型是Y
子类,则对象x
可以转换为类Y
Or, in other words, if there is a path from runtime type of x
to Y
. 或者,换句话说,如果存在从运行时类型
x
到Y
的路径。 By "runtime type" i mean the type of object (the one used when constructing object) as opposed to type of variable (the one from variable declaration). “运行时类型”是指对象的类型(构造对象时使用的对象),而不是变量类型(来自变量声明的对象)。
This is valid: 这是有效的:
b = new B();
(B)(I)b;
Object stored in b
has type B
. 存储在
b
对象具有类型B
It's casted to I
and then back to B
. 它被铸造给
I
,然后回到B
B
is a subclass of both of them. B
是它们的子类。 Cast to I
doesn't actually do anything and is meant only to confuse you. 施展到
I
实际上并没有做任何事情,只是为了让你感到困惑。
However, neither of those is valid: 但是,这些都不是有效的:
a = new A();
(B)(I)a;
(B)a;
They will both fail with exception: java.lang.ClassCastException: A cannot be cast to B
. 它们都会因异常而失败:
java.lang.ClassCastException: A cannot be cast to B
a
has type A
which is not a subclass of B
. a
具有类型A
,它不是B
的子类。 There is a relation between A
and B
, but it's in the opposite direction - B
is a subclass of A
. A
和B
之间存在关系,但它的方向相反 - B
是A
的子类。
For more detailed explanation see here: http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html 有关更详细的说明,请参见此处: http : //docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
The only thing of relevance to answering the question in your coding sample is the following: 与您的编码示例中回答问题唯一相关的是以下内容:
class B extends A{}
This means that B is a subclass of A. Subclasses can be cast to super class types, but super class cannot be cast to subclass types. 这意味着B是A的子类。子类可以转换为超类类型,但超类不能转换为子类类型。
Therefore, A cannot be cast to type B. 因此,A不能转换为B类。
Why? 为什么? Think about the logic this way:
以这种方式思考逻辑:
is a type of
Programming_language
, but Programming_language
is not a type of 是一种
Programming_language
,但Programming_language
不是一种类型
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.