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.