Shadowing Variables in Java Demystified

Posted on June 27, 2008. Filed under: Java Basics | Tags: , , , |

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.

/*
This Code Snippet shows shadowing an Instance Variable by declaring a local variable of the same name either directly or in the argument
*/

class Person
{

static int age=20;
static 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: ” +age);
adjustAge(age);
System.out.println(“Adjusted Age is: ” +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.

Make a Comment

Make A Comment: ( 3 so far )

blockquote and a tags work here.

3 Responses to “Shadowing Variables in Java Demystified”

RSS Feed for Java PitStop Comments RSS Feed

wouldnt it be
this.age = age+20;
???

i am a bit confused in this regard whether “this” work fine with the “static”

That’s the catch there. this is not required for static members. U can use the name of the class. If in the earlier example had Person.age would have been used in adjustAge() then we would have got the desired result.

This is nothing but Shadowing.


Where's The Comment Form?

Liked it here?
Why not try sites on the blogroll...