When we create a variable in both parent and child classes with the same name and try to access it using a parent’s class reference, which is holding a child class’s object, then what do we get?
In order to understand this, let us consider the example below where we declare a variable x
with the same name in both Parent
and Child
classes.
class Parent {
// Declaring instance variable by name `x`
String x = "Parent`s Instance Variable";
public void print() {
System.out.println(x);
}
}
class Child extends Parent {
// Hiding Parent class's variable `x` by defining a variable in child class with same name.
String x = "Child`s Instance Variable";
@Override
public void print() {
System.out.print(x);
// If we still want to access variable from super class, we do that by using `super.x`
System.out.print(", " + super.x + "\n");
}
}
```
And now, if we try to access `x` using below code, `System.out.println(parent.x)` will print:
```
Parent parent = new Child();
System.out.println(parent.x) // Output – Parent`s Instance Variable
Well generally, we say that the `Child` class will override the variable declared in the `Parent` class, and `parent.x` will give us whatever the `Child`'s object is holding. Because it is the same thing, it happens while we do the same kind of operation on methods.
But, actually, it is not, and the `parent.x` will give us the value of the Parent`s Instance Variable, which is declared in the `Parent` class — but why?
This is because variables in Java do not follow polymorphism and overriding is only applicable to methods, not variables. And when an instance variable in a `child` class has the same name as an instance variable in a `parent` class, then the instance variable is chosen from the reference type.
In Java, when we define a variable in a `Child` class with a name that we have already used to define a variable in the `Parent` class, the Child class's variable hides the parent's variable, even if their types are different. And this concept is known as **variable hiding**.
In other words, when the `child` and `parent` class both have a variable with the same name, the `Child` class's variable hides the `Parent` class's variable. You can read more on variable hiding in the article: [What is Variable Shadowing and Hiding in Java](https://programmingmitra.com/2018/02/what-is-variable-shadowing-and-hiding.html).
#java #tutorial #overriding #method overriding #variable hiding #sub class #super class