...
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 | ||
---|---|---|
| ||
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 | ||
---|---|---|
| ||
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 | ||
---|---|---|
| ||
class MyVector { private void doLogic() { for (int i = 0; i < 10; i++) {/* ... */} for (int i = 0; i < 20; i++) {/* ... */} } } |
...
Puzzle 67, "All Strung Out" | |
Item 16, "Prefer Interfaces to Abstract Classes" | |
§6.3, "Placement" | |
| |
[JLS 2011] | §6.4.1, "Shadowing" |
...