Variable Shadowing in Java

In the previous post can we override static method in java? we saw that methods in java classes can be override(or hide in case of static method). Now we will see whether it is possible to hide a variable. Hiding a variable is also called shadowing. A variable can be shadowed if another variable with same name exists in its scope. So what is a scope?


Scope is a region of program within which a variable can be accessed. Each type of variable have their own scope. So if there are two variables with same name in the same scope then they will be shadowed. There are different scenarios in which variables are shadowed.

Local variable can shadow instance variable

Click to find more details about local variable and instance variable.

Ok, now consider the following example.

In the example given above, there are two variables with same name myVariable. First declaration is instance variable and second one is local variable in method testVariable and when we execute this program it gives and output as follows.

And it is because instance variable myVariable is shadowed in method testVariable by local variable myVariable.

Parameter variable can shadow Instance variable

Instance variables can get shadowed by parameter variables also. To check that consider the following example.

if you execute the above program you will get following output.

So we can say that in method testVariable the instance variable myVariable is shadowed by parameter variable myVariable.

Ok; if you want to access the instance variable in the method testVariable what can we do? We can use the this keyword as follows.

Try it out.

Child variable can shadow Parent variable

If parent class and child class have variable with same name, then variable in the child class can shadow variable in the parent class.
For example, if we have a base class as follows

and a subclass as follows.

The output of the program will be

Here the variable myVariable from the super class SuperClass is shadowed by myVariable of ChildClass.

If you want to access the variable from super class you can cast the instance variable to super class as follows.

Ok thats about variable shadowing.
Now before concluding, just check another scenario. Can you predict the output of the following?

The output of the above program is not ChildClass but it is as follows.

If you found surprised, this is not with the shadowing but in Java, variables are referenced by the reference types and not with the object they are holding.

Leave a Comment

Your email address will not be published. Required fields are marked *