6.3.1 Hiding Names

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.

The example:


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);
	}
}

produces the output:

x=0, Test.x=1

This example declares:

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.

This means that:

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:

The example:

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]); } }

compiles and prints:

1

using the class Vector declared here in preference to class java.util.Vector that might be imported on demand.