next up previous
Next: Week 3 Up: Varieties of Variables Previous: Variable Summary

Shadowing: When Scopes Collide

This all sounds very nice, but what happens when we declare a variable say called myVar when it is in the scope of a variable that has already been declared as myVar? Can we use the name again?

The answer is sometimes, and when we can do this, it is called shadowing: the second declaration of the variable is said to shadow the first. (If you think of the scope of a variable as the places in the code where it's visible, declaring another variable using the same name casts a shadow over some part of the program. The original variable isn't visible in the shadow, but the new one is....)

In the example below, y in the method main shadows the class variable y. When a variable is shadowed, we cannot refer to it by it's simple name; we must use the more precise qualified name.


     class someClass{
	private int instVar = 0;
	public void printinstVar(){
	     int instVar = 2;
	     System.out.println(``Instvar = `` + instVar); 
	     System.out.println(``this.Instvar = `` + this.instVar); 
                     }
    }

     class Test {
             static int y = 1;
             public static void main(String[] args) {
                     int y = 0;
                     System.out.print("y=" + y);
                     System.out.println(", Test.y=" + Test.y);

	someClass c = new someClass();
                     c.printinstVar();
             }
     }

In this case, we must refer to the class variable y as Test.y while in the method main so as not to confuse it with the local variable y.

While in the method printinstVar(), if we use the name instVar we are referring to the local variable. To access the instance variable instVar, we must use the qualified name this.instVar which means 'the instVar belonging to this object' , where 'this object' is the object that we sent to the method.

Note that we can't make two declarations using the same variable name where it doesn't really make sense: for example, we can't declare the same variable twice as a local variable. The reason it makes sense above is that the compiler is looking in different places for the value of the variable this.instVar and instVar: one is in an object and the other is in a frame on the run-time stack. Generally, if two declarations create local variables with the same name that are in the same frame on the run-time stack, instance variables of the same name which are in the same object, or class variables of the same name which are in the same class definition, then the compiler will give us an error.


next up previous
Next: Week 3 Up: Varieties of Variables Previous: Variable Summary
Chris Trendall
Copyright ©Chris Trendall, 2001. All rights reserved.

2001-12-09