Restriction on shadowing variables

Restriction on shadowing variables

The Java Language Specification 3.0 §14.4.2 defines a restriction on variable shadowing to help detect bugs. Basically, you can do

  1. public class Person {
  2.  
  3.   private int age;
  4.  
  5.   public void setAge(final int age) {
  6.     this.age = age;
  7.   }
  8. }

and

  1. public class Foobar {
  2.  
  3.   public static void main(String[] args) {
  4.     {
  5.       int i = 0;
  6.     }
  7.     {
  8.       int i = 0;
  9.     }
  10.   }
  11. }

but not

  1. public class Foobar {
  2.  
  3.   public static void main(String[] args) {
  4.     int i = 0;
  5.     for(int i = 0; i < 10; ++i) { // compile error
  6.     }
  7.   }
  8. }

or

  1. public class Foobar {
  2.  
  3.   public static void main(String[] args) {
  4.     int i = 0;
  5.     {
  6.       int i = 0; // compile error
  7.     }
  8.   }
  9. }

Here are some excerpts from §14.4.2:

The name of a local variable v may not be redeclared as a local variable of the directly enclosing method, constructor or initializer block within the scope of v, or a compile-time error occurs. The name of a local variable v may not be redeclared as an exception parameter of a catch clause in a try statement of the directly enclosing method, constructor or initializer block within the scope of v, or a compile-time error occurs. However, a local variable of a method or initializer block may be shadowed (§6.3.1) anywhere inside a class declaration nested within the scope of the local variable.

If a declaration of an identifier as a local variable of the same method, constructor, or initializer block appears within the scope of a parameter or local variable of the same name, a compile-time error occurs.

This restriction helps to detect some otherwise very obscure bugs. A similar restriction on shadowing of members by local variables was judged impractical, because the addition of a member in a superclass could cause subclasses to have to rename local variables. Related considerations make restrictions on shadowing of local variables by members of nested classes, or on shadowing of local variables by local variables declared within nested classes unattractive as well.

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.

More information about formatting options

To prevent automated spam submissions leave this field empty.