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:

public class Main {
public static void main(String[] args) {
Child child = new Child();
// child
System.out.println(((Parent) child).getName());
// parent
System.out.println(((Parent) child).name);
// child
System.out.println(child.getName());
// child
System.out.println(child.name);
}
}
class Parent {
String name = "parent";
public String getName() {
return name;
}
}
class Child extends Parent {
String name = "child";
@Override
public String getName() {
return name;
}
}

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.

public class Main {
public static void main(String[] args) {
Child child = new Child();
// parent
System.out.println(((Parent) child).getName());
// parent
System.out.println(((Parent) child).name);
// parent
System.out.println(child.getName());
// child
System.out.println(child.name);
}
}
class Parent {
String name = "parent";
public String getName() {
return name;
}
}
class Child extends Parent {
String name = "child";
// @Override
// public String getName() {
// return name;
// }
}

References


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