Advertisement
Online Test Banks
Score higher
See Online Test Banks
eLearning
Learning anything is easy
Browse Online Courses
Mobile Apps
Learning on the go
Explore Mobile Apps
Dummies Store
Shop for books and more
Start Shopping

Shadowed Classes or Variables in Java

Shadowing refers to the practice in Java programming 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).

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 to access the variable between the declaration and the initialization, the Java compiler displays an error message.

Because shadowing is a common source of errors, you will want to avoid using it as much as possible.

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement
Advertisement

Inside Dummies.com

Dummies.com Sweepstakes

Win an iPad Mini. Enter to win now!