Java Variables Hiding and Method Overriding

Method Overriding and Variable Hiding

In Java, methods are overridden, but variables can only be hidden.

In the case of method overriding, overriding methods completely replace the inherited methods but in variable hiding, the child class hides the inherited variables instead of replacing them which basically means that the object of Child class contains both variables but Child’s variable hides Parent’s variable.[1]_

Example Code

We can test the theory by the following example:

Method getName() in Parent is overridden by Child's getName(), so ((Parent) child).getA() and child.getA() both get the output "child". is only hidden by, so ((Parent) child).name gets "parent", gets "child"

If we comment the method getName() in Child class as the following, cause method getName() in parent is not overridden, ((Parent) child).getName() and child.getName() both get "parent".
((Parent) child).name gets "parent", gets "child" because name is still hidden.


  1. Variables in Java Do Not Follow Polymorphism and Overriding ↩︎