Java Reference
In-Depth Information
private static double OVERDRAFT_FEE = 5;
}
Here, the unqualified name OVERDRAFT_FEE refers to
BankAccount.OVERDRAFT_FEE .
8.8.3 Overlapping Scope
Problems arise if you have two identical variable names with overlapping scope.
This can never occur with local variables, but the scopes of identically named local
variables and instance fields can overlap. Here is a purposefully bad example.
public class Coin
{
. . .
public double getExchangeValue(double
exchangeRate)
{
double value ; // Local variable
. . .
return value;
}
private String name;
private double value ; // Field with the same name
}
Inside the getExchangeValue method, the variable name value could
potentially have two meanings: the local variable or the instance shadow a field.
The Java language specifies that in this situation the local variable wins out. It
shadows the instance field. This sounds pretty arbitrary, but there is actually a good
reason: You can still refer to the instance field as this.value .
value = this.value * exchangeRate;
It isn't necessary to write code like this. You can easily change the name of the
local variable to something else, such as result .
A local variable can shadow a field with the same name. You can access the
shadowed field name by qualifying it with the this reference.
Search WWH ::




Custom Search