我正在测试Java并注意到“物理”转换会改变对象的属性。我不太明白在使用强制转换时Java内部实际发生了什么,但我注意到了这一点:
这是我的超级班InstanceVariable
:
package inheritance;
public class InstanceVariable {
public int x = 1;
}
这是一个继承自它的类:
package inheritance;
public class InstanceVariable1 extends InstanceVariable {
public int x = 100;
public static int y = 2;
public static void main(String[] args) {
InstanceVariable1 one = new InstanceVariable1();
InstanceVariable two = new InstanceVariable1();
System.out.println(one.x + " " + two.x);
one = (InstanceVariable) one; //This is illegal
}
}
首先,实例化的实例变量被子类覆盖。其次,我可以隐式地将超类(即InstanceVariable
)强制转换为two
,但出于某种原因,我无法将其明确地转换为one
?这是什么原因?