[英]Java upcasting and downcasting and inheritance
Let say there is one superclass and two subclasses.假设有一个超类和两个子类。
Why Java doesn't allow this scenario:为什么 Java 不允许这种情况:
B -> A (A is superclass of class B)
C -> A
ObjectC c = (ObjectC)(ObjectA)b;
This way I could map common properties from object b to object c.这样我就可以将公共属性从对象 b 映射到对象 c。
With (ObjectA)b
you have an expression, if evaluated results in a reference of type ObjectA (ObjectA ab = (ObjectA)b).使用
(ObjectA)b
您有一个表达式,如果计算结果为 ObjectA (ObjectA ab = (ObjectA)b) 类型的引用。 The actual type of the instantiated object (in memory) does not change, only the handle with you hold it (the reference) changes.实例化对象的实际类型(在内存中)不会改变,只有你持有它的句柄(引用)会改变。 You cannot cast that reference to
ObjectC
, because the underlying object instance (originally b) is of type ObjectB
.您不能将该引用转换为
ObjectC
,因为基础对象实例(最初为 b)的类型为ObjectB
。
Let's say we allowed what you wrote in the question ObjectC c = (ObjectC)(ObjectA)b
.假设我们允许您在问题
ObjectC c = (ObjectC)(ObjectA)b
所写的内容。 If you evaluate that you'd get a reference of type ObjectC to the instantiated object b.如果你评估你会得到一个 ObjectC 类型的引用到实例化的对象 b。 Let's say ObjectC has a method called run(), but of course, ObjectB does not have to have a run() method.
假设 ObjectC 有一个名为 run() 的方法,但当然,ObjectB 不必有 run() 方法。 What would happen when you call
c.run()
?当你调用
c.run()
会发生什么?
If you want to map common properties from object b to object c you have to use their common base-class and put common properties there.如果要将公共属性从对象 b 映射到对象 c,则必须使用它们的公共基类并将公共属性放在那里。
Edited with better explanation.编辑有更好的解释。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.