2

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.

2 Answers2

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.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • as the return type is Child's getObject() method is Child then how it calling the parent's x field? –  Jun 05 '16 at 10:25
  • 1
    Field bindings are resolved at compile-time, so the compiler knows whether to read `Parent.x` or `Child.x`. – chrylis -cautiouslyoptimistic- Jun 05 '16 at 10:27
  • 2
    @LetDoit The static (compile time) return type is `Parent` (before you made the change). The dynamic (runtime) type is `Child`. It's the compile time type which determines which members can be accessed. – Eran Jun 05 '16 at 10:28
  • Why would Java let one parameter shadow the other. There should, at least, be a warning in compile time. There is an explanation from Jon Skeet here https://stackoverflow.com/a/772694/5636313. But, to me, the reasons he has listed shouldn't be much problem. – Farid Jun 03 '21 at 13:48
-1

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.

user207421
  • 305,947
  • 44
  • 307
  • 483
Ubercool
  • 1,029
  • 2
  • 14
  • 29