Site icon Experiences Unlimited

Shadowing Variables in Java Demystified

One of the meanings of the word “Shadow” in the Oxford Dictionary is “a weak or less good version”. Shadowing in Java is also something similar. One can shadow a variable in several ways. I would try to describe the one most comman ways which would trip most of us i.e. “Hiding an instance variable by shadowing it with a local Variable”. What exactly is Shadowing in Java? Shadowing is nothing but redeclaring a variable that’s already been declared somewhere else. The effect of Shadowing is to hide the previously declared variable in such a way that it may look as though you’re using the hidden variable, but you’re actually using the shadowing variable (The Code Snippet below will make it more clear). This most of the times happens by accident and causes hard-to-find bugs.

person class Person
{
int age=20;
void adjustAge(int age)
 {
 age=age+20;
 System.out.println("The Age in adjustAge() is "+ age);
 }
 public static void main(String[] args)
 {
 Person p = new Person();
 System.out.println("Age is: " +p.age);
 p.adjustAge(p.age);
 System.out.println("Adjusted Age is: " +p.age);
 }
}

The above code snippet is trying to change the age of the person, adding 20 to the existing age, which is done by the static method adjustAge(). So what will be the output? Any Gusses?

Output:

Age is: 20
The Age in adjustAge() is 40
Adjusted Age is:20

Code Demystified:

The line in the code which is bold and read in color is the main culprit i.e “age=age+20;“. Can anyone guess what is the line exactly doing? It is actually updating the local variable “age” and not the instance variable “age“, i.e the instance variable is shadowed by the Local Variable. And the scope of the Local Variable is the block of code in which it is declared. So, the last Print Statement actually access the unchanged instance variable “age“. Shadowing can also involve object references, in which case it becomes even more interesting to deal with.

For people preparing for SCJP, you can expect few questions on Shadowing.

Update: Have edited the post to add a relevant and useful examples. Earlier I had used static variables which weren’t that clear to understand. Also the corrected version of the above code would be to use:

this.age=age+20;

at Line 6 in the above code. So when you use “this” or class name for static variables- You refer to the field present in the class and not the local variable of the same name.

Exit mobile version