I was reading a book and came across the term Shadow Variables in Java but there was no description for it. Eventually what are these variables used for and how are they implemented?
-
In Java, there are three kinds of variables: local variables, instance variables, and class variables. Variables have their scopes. Different kinds of variables have different scopes. A variable is shadowed if there is another variable with the same name that is closer in scope. In other words, referring to the variable by name will use the one closest in scope , the one in the outer scope is shadowed.– SonalPMCommented Oct 10, 2014 at 10:26
-
A quick food for thought on shadowing can be seen in this post : stackoverflow.com/questions/8814153/…– lft93rytCommented Mar 21, 2017 at 7:38
Add a comment
|
1 Answer
Instead of providing my own description i may ask you to read about it for example here: http://en.wikipedia.org/wiki/Variable_shadowing. Once you understood the shadowing of variables i recommend you proceed reading about overlaying/ shadowed methods and visibility in general to get a full understanding of such terms.
Actually since the question was asked in Terms of Java here is a mini-example:
public class Shadow {
private int myIntVar = 0;
public void shadowTheVar(){
// since it has the same name as above object instance field, it shadows above
// field inside this method
int myIntVar = 5;
// If we simply refer to 'myIntVar' the one of this method is found
// (shadowing a seond one with the same name)
System.out.println(myIntVar);
// If we want to refer to the shadowed myIntVar from this class we need to
// refer to it like this:
System.out.println(this.myIntVar);
}
public static void main(String[] args){
new Shadow().shadowTheVar();
}
}
-
Try not to use shadow variables. It confuses code readers. Commented Sep 29, 2017 at 15:45