How fields work in Polymorphism Java? [duplicate]

泪湿孤枕 提交于 2019-12-18 07:09:37

问题


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();
    }
}

Output:

Child Object
10

But when I change return type of Parent class's getObject to Child.

public Child getObject() {
        System.out.println("Parent Object");
        return new Child();
    }

Then I'm getting Output

Child Object
20

I know fields are not included in Polymorphism.

I'm confused result should be same in above example after and before changing return type of Parent's getObject(); method.


回答1:


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.

Therefore p.getObject().x returns the value of a different x member when you change the return type of getObject() from Parent to Child.




回答2:


Rule of thumb is - Class member are not overridden as methods are. The value returned depends on the reference using which it is accessed. If you are accessing using the parent reference the parent's property will be returned and if the reference is of child class than child's property will be returned.



来源:https://stackoverflow.com/questions/37640772/how-fields-work-in-polymorphism-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!