Building Variable Shadowing In Java
By: Vaibhav Pandey
There are many ways so that we can shadow our variables. One way is to hide an instance variable by shadowing it by local variable. Shadowing happens when we redecalre a variable that has already been declared somewhere else in the program. The effect of shadowing is to hide certain variables in such a way that it may look as though you are using the hidden variable,but you are actually using shadowed variable.
Typically it happens by accidents which returns some hard to find bugs,and there are reasons where you wish to use variable shadowing.
I assume you have no knowledge of Shadowing previously that’s why here is one example followed by a practice question.
Example:-Shadowing instance variable with a local variable.
class dimensions{
static int height=20;
static void changeHeight(int height){
height=height+400;
System.out.println(”height in changeHeight “+height);
}
public static void main(String a[]){
dimension dim=new dimension();
System.out.println(”height before changeHeight”+height);
changeHeight(height);
System.out.println(”height after changeHeight”+height);
}
}
When you will execute the above code the output would be:-
height before changeHeight 20
height in changeHeight 420
height after changeHeight 20
It is quite simple to understand since this is a call by value method call we call method changeHeight() by passing the copy of height instance variable.Since call by value passes value in bits thus local variable gets all the value of instance variable and thus all the operations are done on local variable rather than instance variable and instance variable remains untouched.
That was quite simple though but solve the following its quite messy.I will appreciate if you solve this and write the solution as a comment.
class MyNumber{
int number=44;
}
class ChangeNumber{
MyNumber mynum=MyNumber();
void changeNumber(MyNumber mynum){
mynum.number=88;
System.out.println(”mynum.number in changeNumber is “+mynum.number);
mynum=new MyNumber();
mynum.number=99;
System.out.println(”mynum.number in changeNumber is now “+mynum.number);
}
public static void main(String a[]){
ChangeNumber chgnum=new ChangeNumber();
System.out.println(”chgnum.mynum.number in changeNumber is “+chgnum.mynum.number);
chgnum.changeNumber(chgnum.mynum);
System.out.println(”chgnum.mynum.number after changeNumber is “+chgnum.mynum.number);
}
}

