Shadowing
Shadowing refers to the practice of using two variables with the same name within scopes that overlap. When you do that, the variable with the higher-level scope is hidden because the variable with lower-level scope overrides it. The higher-level variable is then “shadowed.”
You can access a shadowed class or instance variable by fully qualifying it — that is, by providing the name of the class that contains it.
For example, consider this program:
public class ShadowApp
{
static int x;
public static void main(String[] args)
{
x = 5;
System.out.println(“x = “ + x);
int x;
x = 10;
System.out.println(“x = “ + x);
System.out.println(”ShadowApp.x = ” +
ShadowApp.x);
}
}
Here is the output:
x = 5
x = 10
x = 10
ShadowApp.x = 5
Here, the first System.out.println statement prints the value of the class variable x. Then, the class variable x is shadowed by the local variable x, whose value is printed by the second System.out.println statement. Finally, the third System.out.println statement prints the shadowed class variable by providing its fully qualified name (ShadowApp.x).
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access