By Overriding and Hiding Methods
The version of the hidden method that is called depends on whether it is called from the superclass or subclass.
i.e. when you call a method that is overridden in a subclass using a superclass reference, the superclass method is called and it gets access to the members of the superclass.
This explains the following, since the link is used for the superclass:
System.out.println(father.i); //why 1? System.out.println(father.j); //why 10? System.out.println(father.getJ()); //why 10?
Similarly for the following:
System.out.println(son.getJ());
since getJ() not defined in Son , the Father version is called, which sees the member defined in the Father class.
If you are reading Hide Fields ; they specifically do not recommend a coding method such as
Generally speaking, we do not recommend hiding fields, as this makes it difficult to read the code.
source share