字段在多态Java中如何工作? [英] How fields work in Polymorphism Java?

查看:81
本文介绍了字段在多态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引用时,Childx成员将隐藏从Parent继承的成员.使用Parent引用时,您会看到Parentx成员.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆