Java Reference
In-Depth Information
The resulting behavior can be classified as shadowing; the method variable renders
the class variable inaccessible within the scope of the method. For example, assigning to
this.val from within the method does not affect the value of the class variable.
Compliant Solution (Field Shadowing)
This compliant solution eliminates shadowing by changing the name of the variable
defined in the method scope from val to newValue :
Click here to view code image
class MyVector {
private int val = 1;
private void doLogic() {
int newValue;
//...
}
}
Noncompliant Code Example (Variable Shadowing)
This example is noncompliant because the variable i defined in the scope of the second
for loop block shadows the definition of the instance variable i defined in the MyVector
class:
Click here to view code image
class MyVector {
private int i = 0;
private void doLogic() {
for (i = 0; i < 10; i++) {/* ... */}
for (int i = 0; i < 20; i++) {/* ... */}
}
}
Compliant Solution (Variable Shadowing)
Inthiscompliantsolution,theloopcounter i isonlydefinedinthescopeofeach for loop
block:
Click here to view code image
 
Search WWH ::




Custom Search