Java Reference
In-Depth Information
• The invocation of println uses a qualified name (§ 6.6 ) Test.x , which uses the
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 ):
Click here to view code image
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
Click here to view code image
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
8.1.2 ) that might be imported on demand.
Search WWH ::




Custom Search