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".
parent.name is only hidden by child.name, so ((Parent) child).name gets "parent", child.name 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", child.name gets "child" because name is still hidden.