I know Variables doesn't exhibit polymorphic behavior and its limited to methods. But below code is bit confusing in returning the type of object.
Its invoking the child method (which is right) and that means it is returning the child object. So why not printing the child variable's value?
class Parent {
int var = 11;
public Parent getInstance() {
System.out.println("In Parent ...");
return new Parent();
}
}
class Child extends Parent {
int var = 22;
public Child getInstance() {
System.out.println("In Child ...");
return new Child();
}
}
public class VariableHiding {
public static void main(String[] args) {
Parent p = new Child();
System.out.println(p.getInstance().var); // something's fishy?
}
}
// Output : In Child ... 11
PS : Its not the duplicate of this one (which talks about variable not taking part in polymorphism, but the one mentioned here returns the object of child obj and that obj holds var of parent instead of its own)