字段在多态Java中如何工作? [英] How fields work in Polymorphism Java?
问题描述
我正在阅读有关Java的面试问题,发现很好的例子,并感到困惑.因为没有很好的/更多的解释可以帮助我理解此示例.这是示例.
I was reading Interview Questions about java and found nice example and got confused. Because there is not well/more explanation that could help me to understand this example. Here is the example.
public class MainClass {
public static void main(String[] args) {
Parent p = new Child();
System.out.println(p.getObject().x);
}
}
class Parent {
int x = 10;
public Parent getObject() {
System.out.println("Parent Object");
return new Child();
}
}
class Child extends Parent {
int x = 20;
public Child getObject() {
System.out.println("Child Object");
return new Child();
}
}
输出:
Child Object
10
但是当我将Parent类的getObject的返回类型更改为Child时.
But when I change return type of Parent class's getObject to Child.
public Child getObject() {
System.out.println("Parent Object");
return new Child();
}
然后我得到输出
Child Object
20
我知道多态性中不包含字段.
I know fields are not included in Polymorphism.
我很困惑,在更改Parent的getObject()的返回类型之前和之后的示例中,结果应该相同.方法.
I'm confused result should be same in above example after and before changing return type of Parent's getObject(); method.
推荐答案
您的Child
类有两个x
成员-一个直接声明的成员,另一个继承自Parent
的成员.使用Child
引用时,Child
的x
成员将隐藏从Parent
继承的成员.使用Parent
引用时,您会看到Parent
的x
成员.
Your Child
class has two x
members - the one it declares directly and the one it inherits from Parent
. When you use a Child
reference, the x
member of Child
hides the one inherited from Parent
. When you use a Parent
reference, you see the x
member of Parent
.
因此,当您将getObject()
的返回类型从Parent
更改为Child
时,p.getObject().x
返回另一个x
成员的值.
Therefore p.getObject().x
returns the value of a different x
member when you change the return type of getObject()
from Parent
to Child
.
这篇关于字段在多态Java中如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!