Hiding Fields in Java Inheritance

大憨熊 提交于 2019-11-28 09:16:56

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?
SiB

As per Overriding and Hiding Methods

The version of the hidden method that gets invoked depends on whether it is invoked from the superclass or the subclass.

i.e. when you invoke a method which is overridden in subclass via a super class reference the super class method is invoked and it access super class members.

This explains following as the reference used is of 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() is not defined in Son a Father version is invoked which sees member defined in the Father class.

If you read Hiding Fields; they specifically don't recommend such method of coding as

Generally speaking, we don't recommend hiding fields as it makes code difficult to read.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!