Hide fields in Java inheritance

Inside the class, a field with the same name as the field in the superclass hides the field of the superclass.

public class Test { public static void main(String[] args) { Father father = new Son(); System.out.println(father.i); //why 1? System.out.println(father.getI()); //2 System.out.println(father.j); //why 10? System.out.println(father.getJ()); //why 10? System.out.println(); Son son = new Son(); System.out.println(son.i); //2 System.out.println(son.getI()); //2 System.out.println(son.j); //20 System.out.println(son.getJ()); //why 10? } } class Son extends Father { int i = 2; int j = 20; @Override public int getI() { return i; } } class Father { int i = 1; int j = 10; public int getI() { return i; } public int getJ() { return j; } } 

Can someone explain the results to me?

+9
source share
2 answers

In java, fields are not polymorphic.

 Father father = new Son(); System.out.println(father.i); //why 1? Ans : reference is of type father, so 1 (fields are not polymorphic) System.out.println(father.getI()); //2 : overridden method called System.out.println(father.j); //why 10? Ans : reference is of type father, so 2 System.out.println(father.getJ()); //why 10? there is not overridden getJ() method in Son class, so father.getJ() is called System.out.println(); // same explaination as above for following Son son = new Son(); System.out.println(son.i); //2 System.out.println(son.getI()); //2 System.out.println(son.j); //20 System.out.println(son.getJ()); //why 10? 
+9
source

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()); //why 10? 

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.

+3
source

Source: https://habr.com/ru/post/924426/


All Articles