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).

TechnicalStuff.eps The scope of a local variable that shadows a class variable doesn’t necessarily begin at the same point that the local variable’s scope begins. The shadowing begins when the local variable is declared, but the local variable’s scope doesn’t begin until the variable is initialized. If you attempt ...

Get Java For Dummies Quick Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.