Java Reference
In-Depth Information
class type name
Test
to access the class variable
x
, because the declaration of
Test.x
is shadowed at this point and cannot be referred to by its simple name.
The keyword
this
can also be used to access a shadowed field
x
, using the form
this.x
.
Indeed, this idiom typically appears in constructors (§
8.8
):
class Pair {
Object first, second;
public Pair(Object first, Object second) {
this.first = first;
this.second = second;
}
}
Here, the constructor takes parameters having the same names as the fields to be ini-
tialized. 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.
Example 6.4.1-2. Shadowing of a Type Declaration by Another Type Declaration
import java.util.*;
class Vector {
int val[] = { 1 , 2 };
}
class Test {
public static void main(String[] args) {
Vector v = new Vector();
System.out.println(v.val[0]);
}
}
The program compiles and prints:
1
using the class
Vector
declared here in preference to the generic class
java.util.Vector