Some declarations may be hidden (§6.3.1) in part of their scope by another declaration of the same name, in which case a simple name cannot be used to refer to the declared entity.
class Test {
static int x = 1;
public static void main(String[] args) {
int x = 0;
System.out.print("x=" + x);
System.out.println(", Test.x=" + Test.x);
}
}
x=0, Test.x=1
Test
static) variable x that is a member of the class Test
main that is a member of the class Test
args of the main method
x of the main method
Since the scope of a class variable includes the entire body of the class (§8.2) the class variable x would normally be available throughout the entire body of the method main. In this example, however, the class variable x is hidden within the body of the method main by the declaration of the local variable x.
A local variable has as its scope the rest of the block in which it is declared (§14.3.2); in this case this is the rest of the body of the main method, namely its initializer "0" and the invocations of print and println.
x" in the invocation of print refers to (denotes) the value of the local variable x.
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 hidden at this point and cannot be referred to by its simple name.
If the standard naming conventions (§6.8) are followed, then hiding that would make the identification of separate naming contexts matter should be rare. The following contrived example involves hiding because it does not follow the standard naming conventions:
class Point { int x, y; }
class Test {
static Point Point(int x, int y) {
Point p = new Point();
p.x = x; p.y = y;
return p;
}
public static void main(String[] args) {
int Point;
Point[] pa = new Point[2];
for (Point = 0; Point < 2; Point++) {
pa[Point] = new Point();
pa[Point].x = Point;
pa[Point].y = Point;
}
System.out.println(pa[0].x + "," + pa[0].y);
System.out.println(pa[1].x + "," + pa[1].y);
Point p = Point(3, 4);
System.out.println(p.x + "," + p.y);
}
}
This compiles without error and executes to produce the output:
0,0 1,1
3,4
Within the body of main, the lookups of Point find different declarations depending on the context of the use:
new Point[2]", the two occurrences of the class instance creation expression "new Point()", and at the start of three different local variable declaration statements, the Point is a TypeName (§6.5.4) and denotes the class type Point in each case.
Point(3, 4)" the occurrence of Point is a MethodName (§6.5.6) and denotes the class (static) method Point.
Point.
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]);
}
}
1
using the class Vector declared here in preference to class java.util.Vector
that might be imported on demand.