Hiding Fields in Java Inheritance

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?

Leave a Comment