Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

According to §6.4.2, "Obscuring," of the Java Language Specification [JLS 2011],

A simple name may occur in contexts where it may potentially be interpreted as the name of a variable, a type, or a package. In these situations, the rules of §6.5 specify that a variable will be chosen in preference to a type, and that a type will be chosen in preference to a package.

...

This compliant solution eliminates shadowing by changing the name of the variable defined in the method scope.:

Code Block
bgColor#ccccff
class MyVector {
  private int val = 1;
  private void doLogic() {
    int newValue;
    //...   
  }
}

...

This example is noncompliant because the variable i defined in the scope of the second for loop block shadows the definition of i defined in the scope of the doLogic() method.:

Code Block
bgColor#FFcccc
class MyVector {
  private int i = 0;
  private void doLogic() {
    for (i = 0; i < 10; i++) {/* ... */}
    for (int i = 0; i < 20; i++) {/* ... */} 
  }
}

...

In this compliant solution, the loop counter i is defined in the scope of each for loop block.:

Code Block
bgColor#ccccff
class MyVector {
  private void doLogic() {
    for (int i = 0; i < 10; i++) {/* ... */}
    for (int i = 0; i < 20; i++) {/* ... */} 
  }
}

...

[Bloch 2005a]

Puzzle 67, "All Strung Out"

[Bloch 2008]

Item 16, "Prefer Interfaces to Abstract Classes"

[Conventions 2009]

§6.3, "Placement"

[FindBugs 2008]

 

[JLS 2011]

§6.4.1, "Shadowing"
§6.4.2, "Obscuring"

§7.5.2, "Type-Import-on-Demand Declarations"

[Kabanov 2009]

 

...