Let Do it Let Do it - 6 months ago 25
Java Question

How fields work in Polymorphism 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();
}
}


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.

Answer

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.