隐藏的字段虽然继承 [英] Hidden fields though inheritance
问题描述
在以下代码示例中:
class Parent {
int x =5;
public Integer aMethod(){
System.out.print("Parent.aMthod ");
return x;
}
}
class Child extends Parent {
int x =6;
public Integer aMethod(){
System.out.print("Child.aMthod ");
return x;
}
}
class ZiggyTest2{
public static void main(String[] args){
Parent p = new Child();
Child c = new Child();
System.out.println(p.x + " " + c.x);
System.out.println(p.aMethod() + " \n");
System.out.println(c.aMethod() + " \n");
}
}
输出:
5 6
Child.aMthod 6
Child.aMthod 6
为什么 p.aMethod()
当px打印6时不打印6?
Why does p.aMethod()
not print 6 when p.x prints 6?
谢谢
哎呀一个小错字:问题应该是为什么当px打印5时p.aMethod()不打印5 - 谢谢@thinksteep
Oops a slight typo: The question should be "why does p.aMethod() not print 5 when p.x print 5" - Thanks @thinksteep
推荐答案
没有多态当您访问类成员字段(实例变量),如 px
时,将执行解析。换句话说,您将从编译时已知的类中获得结果,而不是运行时已知的结果。
There's no polymorphic resolution being done when you access class member fields (instance variables) like p.x
. In other words, you'll get the results from the class that's known at compile time, not what is known at run time.
对于方法调用,这是不同的。它们在运行时被分派给引用指向的实际类的对象,即使引用本身具有超类型。 (在VM中,这通过 invokevirtual
操作码发生,请参阅例如 http://java.sun.com/docs/books/jvms/second_edition/html/Instructions2.doc6.html#invokevirtual )。
For method calls this is different. They are dispatched at run time to an object of the actual class the reference points to, even if the reference itself has a super type. (in the VM this happens via the invokevirtual
opcode, see e.g. http://java.sun.com/docs/books/jvms/second_edition/html/Instructions2.doc6.html#invokevirtual).
这篇关于隐藏的字段虽然继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!