If a name declared as a local variable is already declared as a field or type name,
then that outer declaration is hidden throughout the scope of the local variable.
The field or type name can almost always (§6.8) still be accessed using an appropriately qualified name. For example, the keyword this
can be used to access a
hidden field x
, using the form this.x
. Indeed, this idiom typically appears in constructors (§8.6):
class Pair { Object first, second; public Pair(Object first, Object second) { this.first = first; this.second = second; } }
In this example, the constructor takes parameters having the same names as the fields to be initialized. This is simpler than having to invent different names for the parameters and is not too confusing in this stylized context. In general, however, it is considered poor style to have local variables with the same names as fields.