Variable shadowing

From Wikipedia, the free encyclopedia
Jump to: navigation, search

In computer programming, variable shadowing occurs when a variable declared within a certain scope (decision block, method, or inner class) has the same name as a variable declared in an outer scope. This outer variable is said to be shadowed. This can lead to confusion, as it may be unclear which variable subsequent uses of the shadowed variable name refer to.

One of the first languages to introduce variable shadowing was ALGOL, which first introduced blocks to establish scopes. It was also permitted by many of the derivative programming languages including C++ and Java.

The C# language breaks this tradition, allowing variable shadowing between an inner and an outer class, and between a method and its containing class, but not between an if-block and its containing method, or between case statements in a switch block.

[edit] Example

The following Java code provides an example of variable shadowing.

class VariableShadowing
{
   static int x = 1;
   public static void main(String[] args)
   {
      // This local variable shadows the class variable
      int x = 100;
      // This statement prints the local variable
      System.out.println("Local variable x = " + x); // 100
      // This statement prints the shadowed variable
      System.out.println("Class variable x = " + VariableShadowing.x); // 1
   }
}

[edit] See also

Personal tools
Namespaces

Variants
Actions
Navigation
Interaction
Toolbox
Print/export