Contents | Prev | Next | Index Java Language Specification
Second Edition


CHAPTER 6

Names


Names are used to refer to entities declared in a program. A declared entity (§6.1) is a package, class type, interface type, member (class, interface, field, or method) of a reference type, parameter (to a method, constructor, or exception handler), or local variable.

Names in programs are either simple, consisting of a single identifier, or qualified, consisting of a sequence of identifiers separated by "." tokens (§6.2).

Every declaration that introduces a name has a scope (§6.3), which is the part of the program text within which the declared entity can be referred to by a simple name.

Packages and reference types (that is, class types, interface types, and array types) have members (§6.4). A member can be referred to using a qualified name N.x, where N is a simple or qualified name and x is an identifier. If N names a package, then x is a member of that package, which is either a class or interface type or a subpackage. If N names a reference type or a variable of a reference type, then x names a member of that type, which is either a class, an interface, a field, or a method.

In determining the meaning of a name (§6.5), the context of the occurrence is used to disambiguate among packages, types, variables, and methods with the same name.

Access control (§6.6) can be specified in a class, interface, method, or field declaration to control when access to a member is allowed. Access is a different concept from scope; access specifies the part of the program text within which the declared entity can be referred to by a qualified name, a field access expression (§15.11), or a method invocation expression (§15.12) in which the method is not specified by a simple name. The default access is that a member can be accessed anywhere within the package that contains its declaration; other possibilities are public, protected, and private.

Fully qualified and canonical names (§6.7) and naming conventions (§6.8) are also discussed in this chapter.

The name of a field, parameter, or local variable may be used as an expression (§15.14.1). The name of a method may appear in an expression only as part of a method invocation expression (§15.12). The name of a class or interface type may appear in an expression only as part of a class literal (§15.8.2), a qualified this expression (§15.8.4), a class instance creation expression (§15.9), an array creation expression (§15.10), a cast expression (§15.16), or an instanceof expression (§15.20.2), or as part of a qualified name for a field or method. The name of a package may appear in an expression only as part of a qualified name for a class or interface type.

6.1 Declarations

A declaration introduces an entity into a program and includes an identifier (§3.8) that can be used in a name to refer to this entity. A declared entity is one of the following:

Constructors (§8.8) are also introduced by declarations, but use the name of the class in which they are declared rather than introducing a new name.

6.2 Names and Identifiers

A name is used to refer to an entity declared in a program.

There are two forms of names: simple names and qualified names. A simple name is a single identifier. A qualified name consists of a name, a "." token, and an identifier.

In determining the meaning of a name (§6.5), the context in which the name appears is taken into account. The rules of §6.5 distinguish among contexts where a name must denote (refer to) a package (§6.5.3), a type (§6.5.5), a variable or value in an expression (§6.5.6), or a method (§6.5.7).

Not all identifiers in programs are a part of a name. Identifiers are also used in the following situations:

In the example:

class Test {
	public static void main(String[] args) {
		Class c = System.out.getClass();
		System.out.println(c.toString().length() +
					args[0].length() + args.length);
	}
}
the identifiers Test, main, and the first occurrences of args and c are not names; rather, they are used in declarations to specify the names of the declared entities. The names String, Class, System.out.getClass, System.out.println, c.toString, args, and args.length appear in the example. The first occurrence of length is not a name, but rather an identifier appearing in a method invocation expression (§15.12). The second occurrence of length is not a name, but rather an identifier appearing in a method invocation expression (§15.12).

The identifiers used in labeled statements and their associated break and continue statements are completely separate from those used in declarations. Thus, the following code is valid:

class TestString {
	char[] value;
	int offset, count;
	int indexOf(TestString str, int fromIndex) {
		char[] v1 = value, v2 = str.value;
		int max = offset + (count - str.count);
		int start = offset + ((fromIndex < 0) ? 0 : fromIndex);
	i:
		for (int i = start; i <= max; i++)
		{
			int n = str.count, j = i, k = str.offset;
			while (n-- != 0) {
				if (v1[j++] != v2[k++])
					continue i;
			} 
			return i - offset;
		}
		return -1;
	}
}
This code was taken from a version of the class String and its method indexOf, where the label was originally called test. Changing the label to have the same name as the local variable i does not obscure (§6.3.2) the label in the scope of the declaration of i. The identifier max could also have been used as the statement label; the label would not obscure the local variable max within the labeled statement.

6.3 Scope of a Declaration

The scope of a declaration is the region of the program within which the entity declared by the declaration can be referred to using a simple name (provided it is visible (§6.3.1)). A declaration is said to be in scope at a particular point in a program if and only if the declaration's scope includes that point.

The scoping rules for various constructs are given in the sections that describe those constructs. For convenience, the rules are repeated here:

The scope of the declaration of an observable (§7.4.3) top level package is all observable compilation units (§7.3). The declaration of a package that is not observable is never in scope. Subpackage declarations are never in scope.

The scope of a type imported by a single-type-import declaration (§7.5.1) or type-import-on-demand declaration (§7.5.2) is all the class and interface type declarations (§7.6) in the compilation unit in which the import declaration appears.

The scope of a top level type is all type declarations in the package in which the top level type is declared.

The scope of a label declared by a labeled statement is the statement immediately enclosed by the labeled statement.

The scope of a declaration of a member m declared in or inherited by a class type C is the entire body of C, including any nested type declarations.

The scope of the declaration of a member m declared in or inherited by an interface type I is the entire body of I, including any nested type declarations.

The scope of a parameter of a method (§8.4.1) or constructor (§8.8.1) is the entire body of the method or constructor.

The scope of a local variable declaration in a block (§14.4.2) is the rest of the block in which the declaration appears, starting with its own initializer (§14.4) and including any further declarators to the right in the local variable declaration statement.

The scope of a local class declared in a block is the rest of the immediately enclosing block, including its own class declaration.

The scope of a local variable declared in the ForInit part of a for statement (§14.13) includes all of the following:

The scope of a parameter of an exception handler that is declared in a catch clause of a try statement (§14.19) is the entire block associated with the catch.

These rules imply that declarations of class and interface types need not appear before uses of the types.

In the example:

package points;
class Point {
	int x, y;
	PointList list;
	Point next;
}
class PointList {
	Point first;
}
the use of PointList in class Point is correct, because the scope of the class declaration PointList includes both class Point and class PointList, as well as any other type declarations in other compilation units of package points.

6.3.1 Shadowing Declarations

Some declarations may be shadowed 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.

A declaration d of a type named n shadows the declarations of any other types named n that are in scope at the point where d occurs throughout the scope of d.

A declaration d of a field, local variable, method parameter, constructor parameter or exception handler parameter named n shadows the declarations of any other fields, local variables, method parameters, constructor parameters or exception handler parameters named n that are in scope at the point where d occurs throughout the scope of d.

A declaration d of a label named n shadows the declarations of any other labels named n that are in scope at the point where d occurs throughout the scope of d.

A declaration d of a method named n shadows the declarations of any other methods named n that are in an enclosing scope at the point where d occurs throughout the scope of d.

A package declaration never shadows any other declaration.

A single-type-import declaration d in a compilation unit c of package p that imports a type named n shadows the declarations of:

throughout c.

A type-import-on-demand declaration never causes any other declaration to be shadowed.

A declaration d is said to be visible at point p in a program if the scope of d includes p, and d is not shadowed by any other declaration at p. When the program point we are discussing is clear from context, we will often simply say that a declaration is visible.

Note that shadowing is distinct from hiding (§8.3, §8.4.6.2, §8.5, §9.3, §9.5). Hiding, in the technical sense defined in this specification, applies only to members which would otherwise be inherited but are not because of a declaration in a subclass. Shadowing is also distinct from obscuring (§6.3.2).

Here is an example of shadowing of a field declaration by a local variable declaration:

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 shadowed 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.4.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:

The following example illustrates the shadowing of one type declaration by another:
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.

6.3.2 Obscured Declarations

A simple name may occur in contexts where it may potentially be interpreted as the name of a variable, a type or a package. In these situations, the rules of §6.5 specify that a variable will be chosen in preference to a type, and that a type will be chosen in preference to a package. Thus, it is may sometimes be impossible to refer to a visible type or package declaration via its simple name. We say that such a declaration is obscured.

Obscuring is distinct from shadowing (§6.3.1) and hiding (§8.3, §8.4.6.2, §8.5, §9.3, §9.5). The naming conventions of §6.8 help reduce obscuring.

6.4 Members and Inheritance

Packages and reference types have members.

This section provides an overview of the members of packages and reference types here, as background for the discussion of qualified names and the determination of the meaning of names. For a complete description of membership, see §7.1, §8.2, §9.2, and §10.7.

6.4.1 The Members of a Package

The members of a package (§7) are specified in §7.1. For convenience, we repeat that specification here:

The members of a package are subpackages and all the top level (§7.6) class (§8) and top level interface (§9) types declared in all the compilation units (§7.3) of the package.

In general, the subpackages of a package are determined by the host system (§7.2). However, the package java always includes the subpackages lang and io and may include other subpackages. No two distinct members of the same package may have the same simple name (§7.1), but members of different packages may have the same simple name.

For example, it is possible to declare a package:

package vector;
public class Vector { Object[] vec; }
that has as a member a public class named Vector, even though the package java.util also declares a class named Vector. These two class types are different, reflected by the fact that they have different fully qualified names (§6.7). The fully qualified name of this example Vector is vector.Vector, whereas java.util.Vector is the fully qualified name of the standard Vector class. Because the package vector contains a class named Vector, it cannot also have a subpackage named Vector.

6.4.2 The Members of a Class Type

The members of a class type (§8.2) are classes (§8.5, §9.5), interfaces (§8.5, §9.5), fields (§8.3, §9.3, §10.7), and methods (§8.4, §9.4). Members are either declared in the type, or inherited because they are accessible members of a superclass or superinterface which are neither private nor hidden nor overridden (§8.4.6).

The members of a class type are all of the following:

Constructors (§8.8) are not members.

There is no restriction against a field and a method of a class type having the same simple name. Likewise, there is no restriction against a member class or member interface of a class type having the same simple name as a field or method of that class type.

A class may have two or more fields with the same simple name if they are declared in different interfaces and inherited. An attempt to refer to any of the fields by its simple name results in a compile-time error (§6.5.7.2, §8.2).

In the example:

interface Colors {
	int WHITE = 0, BLACK = 1;
}
interface Separates {
	int CYAN = 0, MAGENTA = 1, YELLOW = 2, BLACK = 3;
}
class Test implements Colors, Separates {
	public static void main(String[] args) {
		System.out.println(BLACK); // compile-time error: ambiguous
	}
}
the name BLACK in the method main is ambiguous, because class Test has two members named BLACK, one inherited from Colors and one from Separates.

A class type may have two or more methods with the same simple name if the methods have different signatures (§8.4.2), that is, if they have different numbers of parameters or different parameter types in at least one parameter position. Such a method member name is said to be overloaded.

A class type may contain a declaration for a method with the same name and the same signature as a method that would otherwise be inherited from a superclass or superinterface. In this case, the method of the superclass or superinterface is not inherited. If the method not inherited is abstract, then the new declaration is said to implement it; if the method not inherited is not abstract, then the new declaration is said to override it.

In the example:

class Point {
	float x, y;
	void move(int dx, int dy) { x += dx; y += dy; }
	void move(float dx, float dy) { x += dx; y += dy; }
	public String toString() { return "("+x+","+y+")"; }
}
the class Point has two members that are methods with the same name, move. The overloaded move method of class Point chosen for any particular method invocation is determined at compile time by the overloading resolution procedure given in §15.12.

In this example, the members of the class Point are the float instance variables x and y declared in Point, the two declared move methods, the declared toString method, and the members that Point inherits from its implicit direct superclass Object (§4.3.2), such as the method hashCode. Note that Point does not inherit the toString method of class Object because that method is overridden by the declaration of the toString method in class Point.

6.4.3 The Members of an Interface Type

The members of an interface type (§9.2) may be classes (§8.5, §9.5), interfaces (§8.5, §9.5), fields (§8.3, §9.3, §10.7), and methods (§8.4, §9.4).The members of an interface are:

An interface may have two or more fields with the same simple name if they are declared in different interfaces and inherited. An attempt to refer to any such field by its simple name results in a compile-time error (§6.5.6.1, §9.2).

In the example:

interface Colors {
	int WHITE = 0, BLACK = 1;
}
interface Separates {
	int CYAN = 0, MAGENTA = 1, YELLOW = 2, BLACK = 3;
}
interface ColorsAndSeparates extends Colors, Separates {
	int DEFAULT = BLACK;								 	// compile-time error: ambiguous
}
the members of the interface ColorsAndSeparates include those members inherited from Colors and those inherited from Separates, namely WHITE, BLACK (first of two), CYAN, MAGENTA, YELLOW, and BLACK (second of two). The member name BLACK is ambiguous in the interface ColorsAndSeparates.

6.4.4 The Members of an Array Type

The members of an array type are specified in §10.7. For convenience, we repeat that specification here.

The members of an array type are all of the following:

The example:

class Test {
	public static void main(String[] args) {
		int[] ia = new int[3];
		int[] ib = new int[6];
		System.out.println(ia.getClass() == ib.getClass());
		System.out.println("ia has length=" + ia.length);
	}
}
produces the output:

true
ia has length=3
This example uses the method getClass inherited from class Object and the field length. The result of the comparison of the Class objects in the first println demonstrates that all arrays whose components are of type int are instances of the same array type, which is int[].

6.5 Determining the Meaning of a Name

The meaning of a name depends on the context in which it is used. The determination of the meaning of a name requires three steps. First, context causes a name syntactically to fall into one of six categories: PackageName, TypeName, ExpressionName, MethodName, PackageOrTypeName, or AmbiguousName. Second, a name that is initially classified by its context as an AmbiguousName or as a Package-OrTypeName is then reclassified to be a PackageName, TypeName, or ExpressionName. Third, the resulting category then dictates the final determination of the meaning of the name (or a compilation error if the name has no meaning).

The use of context helps to minimize name conflicts between entities of different kinds. Such conflicts will be rare if the naming conventions described in §6.8 are followed. Nevertheless, conflicts may arise unintentionally as types developed by different programmers or different organizations evolve. For example, types, methods, and fields may have the same name. It is always possible to distinguish between a method and a field with the same name, since the context of a use always tells whether a method is intended.

6.5.1 Syntactic Classification of a Name According to Context

A name is syntactically classified as a PackageName in these contexts:

A name is syntactically classified as a TypeName in these contexts:

A name is syntactically classified as an ExpressionName in these contexts:

A name is syntactically classified as a MethodName in this context:

A name is syntactically classified as a PackageOrTypeName in these contexts:

A name is syntactically classified as an AmbiguousName in these contexts:

6.5.2 Reclassification of Contextually Ambiguous Names

An AmbiguousName is then reclassified as follows:

package org.rpgpoet;
import java.util.Random;
interface Music { Random[] wizards = new Random[4]; }
and then consider this example code in another package:

package bazola;
class Gabriel {
	static int n = org.rpgpoet.Music.wizards.length;
}
First of all, the name org.rpgpoet.Music.wizards.length is classified as an ExpressionName because it functions as a PostfixExpression. Therefore, each of the names:

org.rpgpoet.Music.wizards
org.rpgpoet.Music
org.rpgpoet
org 
is initially classified as an AmbiguousName. These are then reclassified:

6.5.3 Meaning of Package Names

The meaning of a name classified as a PackageName is determined as follows.

6.5.3.1 Simple Package Names

If a package name consists of a single Identifier, then this identifier denotes a top level package named by that identifier. If no top level package of that name is in scope (§7.4.4), then a compile-time error occurs.

6.5.3.2 Qualified Package Names

If a package name is of the form Q.Id, then Q must also be a package name. The package name Q.Id names a package that is the member named Id within the package named by Q. If Q does not name an observable package (§7.4.3), or Id is not the simple name an observable subpackage of that package, then a compile-time error occurs.

6.5.4 Meaning of PackageOrTypeNames

6.5.4.1 Simple PackageOrTypeNames

If the PackageOrTypeName, Q, occurs in the scope of a type named Q, then the PackageOrTypeName is reclassified as a TypeName.

Otherwise, the PackageOrTypeName is reclassified as a PackageName. The meaning of the PackageOrTypeName is the meaning of the reclassified name.

6.5.4.2 Qualified PackageOrTypeNames

Given a qualified PackageOrTypeName of the form Q.Id, if the type or package denoted by Q has a member type named Id, then the qualified PackageOrTypeName name is reclassified as a TypeName.

Otherwise, it is reclassified as a PackageName. The meaning of the qualified PackageOrTypeName is the meaning of the reclassified name.

6.5.5 Meaning of Type Names

The meaning of a name classified as a TypeName is determined as follows.

6.5.5.1 Simple Type Names

If a type name consists of a single Identifier, then the identifier must occur in the scope of a declaration of a type with this name, or a compile-time error occurs.

It is possible that the identifier occurs within the scope of more than one type with that name, in which case the type denoted by the name is determined as follows:

This order for considering type declarations is designed to choose the most explicit of two or more applicable type declarations.

6.5.5.2 Qualified Type Names

If a type name is of the form Q.Id, then Q must be either a type name or a package name. If Id names exactly one type that is a member of the type or package denoted by Q, then the qualified type name denotes that type. If Id does not name a member type (§8.5, §9.5) within Q, or the member type named Id within Q is not accessible (§6.6), or Id names more than one member type within Q, then a compile-time error occurs.

The example:

package wnj.test;
class Test {
	public static void main(String[] args) {
		java.util.Date date =
			new java.util.Date(System.currentTimeMillis());
		System.out.println(date.toLocaleString());
	}
}
produced the following output the first time it was run:

Sun Jan 21 22:56:29 1996
In this example the name java.util.Date must denote a type, so we first use the procedure recursively to determine if java.util is an accessible type or a package, which it is, and then look to see if the type Date is accessible in this package.

6.5.6 Meaning of Expression Names

The meaning of a name classified as an ExpressionName is determined as follows.

6.5.6.1 Simple Expression Names

If an expression name consists of a single Identifier, then:

In the example:

class Test {
	static int v;
	static final int f = 3;
	public static void main(String[] args) {
		int i;
		i = 1;
		v = 2;
		f = 33;										// compile-time error
		System.out.println(i + " " + v + " " + f);
	}
}
the names used as the left-hand-sides in the assignments to i, v, and f denote the local variable i, the field v, and the value of f (not the variable f, because f is a final variable). The example therefore produces an error at compile time because the last assignment does not have a variable as its left-hand side. If the erroneous assignment is removed, the modified code can be compiled and it will produce the output:

1 2 3

6.5.6.2 Qualified Expression Names

If an expression name is of the form Q.Id, then Q has already been classified as a package name, a type name, or an expression name:

class Point {
	int x, y;
	static int nPoints;
}
class Test {
	public static void main(String[] args) {
		int i = 0;
		i.x++;			// compile-time error
		Point p = new Point();
		p.nPoints();	// compile-time error
	}
}
encounters two compile-time errors, because the int variable i has no members, and because nPoints is not a method of class Point.

6.5.7 Meaning of Method Names

A MethodName can appear only in a method invocation expression (§15.12). The meaning of a name classified as a MethodName is determined as follows.

6.5.7.1 Simple Method Names

If a method name consists of a single Identifier, then Identifier is the method name to be used for method invocation. The Identifier must name at least one method of a class or interface within whose declaration the Identifier appears. See §15.12 for further discussion of the interpretation of simple method names in method invocation expressions.

6.5.7.2 Qualified Method Names

If a method name is of the form Q.Id, then Q has already been classified as a package name, a type name, or an expression name. If Q is a package name, then a compile-time error occurs. Otherwise, Id is the method name to be used for method invocation. If Q is a type name, then Id must name at least one static method of the type Q. If Q is an expression name, then let T be the type of the expression Q; Id must name at least one method of the type T. See §15.12 for further discussion of the interpretation of qualified method names in method invocation expressions.

6.6 Access Control

The Java programming language provides mechanisms for access control, to prevent the users of a package or class from depending on unnecessary details of the implementation of that package or class. If access is permitted, then the accessed entity is said to be accessible.

Note that accessibility is a static property that can be determined at compile time; it depends only on types and declaration modifiers. Qualified names are a means of access to members of packages and reference types; related means of access include field access expressions (§15.11) and method invocation expressions (§15.12). All three are syntactically similar in that a "." token appears, preceded by some indication of a package, type, or expression having a type and followed by an Identifier that names a member of the package or type. These are collectively known as constructs for qualified access.

Access control applies to qualified access and to the invocation of constructors by class instance creation expressions (§15.9) and explicit constructor invocations (§8.8.5). Accessibility also affects inheritance of class members (§8.2), including hiding and method overriding (§8.4.6.1).

6.6.1 Determining Accessibility

6.6.2 Details on protected Access

A protected member or constructor of an object may be accessed from outside the package in which it is declared only by code that is responsible for the implementation of that object.

6.6.2.1 Access to a protected Member

Let C be the class in which a protected member m is declared. Access is permitted only within the body of a subclass S of C. In addition, if Id denotes an instance field or instance method, then:

6.6.2.2 Qualified Access to a protected Constructor

Let C be the class in which a protected constructor is declared and let S be the innermost class in whose declaration the use of the protected constructor occurs. Then:

6.6.3 An Example of Access Control

For examples of access control, consider the two compilation units:

package points;
class PointVec { Point[] vec; }
and:

package points;
public class Point {
	protected int x, y;
	public void move(int dx, int dy) { x += dx; y += dy; }
	public int getX() { return x; }
	public int getY() { return y; }
}
which declare two class types in the package points:

See §6.6.7 for an example of how the protected access modifier limits access.

6.6.4 Example: Access to public and Non-public Classes

If a class lacks the public modifier, access to the class declaration is limited to the package in which it is declared (§6.6). In the example:

package points;
public class Point {
	public int x, y;
	public void move(int dx, int dy) { x += dx; y += dy; }
}
class PointList {
	Point next, prev;
}
two classes are declared in the compilation unit. The class Point is available outside the package points, while the class PointList is available for access only within the package.

Thus a compilation unit in another package can access points.Point, either by using its fully qualified name:

package pointsUser;
class Test {
	public static void main(String[] args) {
		points.Point p = new points.Point();
		System.out.println(p.x + " " + p.y);
	}
}
or by using a single-type-import declaration (§7.5.1) that mentions the fully qualified name, so that the simple name may be used thereafter:

package pointsUser;
import points.Point;
class Test {
	public static void main(String[] args) {
		Point p = new Point();
		System.out.println(p.x + " " + p.y);
	}
}
However, this compilation unit cannot use or import points.PointList, which is not declared public and is therefore inaccessible outside package points.

6.6.5 Example: Default-Access Fields, Methods, and Constructors

If none of the access modifiers public, protected, or private are specified, a class member or constructor is accessible throughout the package that contains the declaration of the class in which the class member is declared, but the class member or constructor is not accessible in any other package.

If a public class has a method or constructor with default access, then this method or constructor is not accessible to or inherited by a subclass declared outside this package.

For example, if we have:

package points;
public class Point {
	public int x, y;
	void move(int dx, int dy) { x += dx; y += dy; }
	public void moveAlso(int dx, int dy) { move(dx, dy); }
}
then a subclass in another package may declare an unrelated move method, with the same signature (§8.3.2) and return type. Because the original move method is not accessible from package morepoints, super may not be used:

package morepoints;
public class PlusPoint extends points.Point {
	public void move(int dx, int dy) {
		super.move(dx, dy);								// compile-time error
		moveAlso(dx, dy);
	}
}
Because move of Point is not overridden by move in PlusPoint, the method moveAlso in Point never calls the method move in PlusPoint.

Thus if you delete the super.move call from PlusPoint and execute the test program:

import points.Point;
import morepoints.PlusPoint;
class Test {
    public static void main(String[] args) {
        PlusPoint pp = new PlusPoint();
        pp.move(1, 1);
	}
}
it terminates normally. If move of Point were overridden by move in PlusPoint, then this program would recurse infinitely, until a StackoverflowError occurred.

6.6.6 Example: public Fields, Methods, and Constructors

A public class member or constructor is accessible throughout the package where it is declared and from any other package, provided the package in which it is declared is observable (§7.4.3). For example, in the compilation unit:

package points;
public class Point {
	int x, y;
	public void move(int dx, int dy) {
		x += dx; y += dy;
		moves++;
	}
	public static int moves = 0;
}
the public class Point has as public members the move method and the moves field. These public members are accessible to any other package that has access to package points. The fields x and y are not public and therefore are accessible only from within the package points.

6.6.7 Example: protected Fields, Methods, and Constructors

Consider this example, where the points package declares:

package points;
public class Point {
	protected int x, y;
	void warp(threePoint.Point3d a) {
		if (a.z > 0)		// compile-time error: cannot access a.z
			a.delta(this);
	}
}
and the threePoint package declares:

package threePoint;
import points.Point;
public class Point3d extends Point {
	protected int z;
	public void delta(Point p) {
		p.x += this.x;		// compile-time error: cannot access p.x
		p.y += this.y;		// compile-time error: cannot access p.y
	}
	public void delta3d(Point3d q) {
		q.x += this.x;
		q.y += this.y;
		q.z += this.z;
	}
}
which defines a class Point3d. A compile-time error occurs in the method delta here: it cannot access the protected members x and y of its parameter p, because while Point3d (the class in which the references to fields x and y occur) is a subclass of Point (the class in which x and y are declared), it is not involved in the implementation of a Point (the type of the parameter p). The method delta3d can access the protected members of its parameter q, because the class Point3d is a subclass of Point and is involved in the implementation of a Point3d.

The method delta could try to cast (§5.5, §15.16) its parameter to be a Point3d, but this cast would fail, causing an exception, if the class of p at run time were not Point3d.

A compile-time error also occurs in the method warp: it cannot access the protected member z of its parameter a, because while the class Point (the class in which the reference to field z occurs) is involved in the implementation of a Point3d (the type of the parameter a), it is not a subclass of Point3d (the class in which z is declared).

6.6.8 Example: private Fields, Methods, and Constructors

A private class member or constructor is accessible only within the class body in which the member is declared and is not inherited by subclasses. In the example:

class Point {
	Point() { setMasterID(); }
	int x, y;
	private int ID;
	private static int masterID = 0;
	private void setMasterID() { ID = masterID++; }
}
the private members ID, masterID, and setMasterID may be used only within the body of class Point. They may not be accessed by qualified names, field access expressions, or method invocation expressions outside the body of the declaration of Point.

See §8.8.8 for an example that uses a private constructor.

6.7 Fully Qualified Names and Canonical Names

Every package, top level class, top level interface, and primitive type has a fully qualified name. An array type has a fully qualified name if and only if its element type has a fully qualified name.

Examples:

In the example:

package points;
class Point { int x, y; }
class PointVec {
	Point[] vec;
}
the fully qualified name of the type Point is "points.Point"; the fully qualified name of the type PointVec is "points.PointVec"; and the fully qualified name of the type of the field vec of class PointVec is "points.Point[]".

Every package, top level class, top level interface, and primitive type has a canonical name. An array type has a canonical name if and only if its element type has a canonical name. A member class or member interface M declared in another class C has a canonical name if and only if C has a canonical name. In that case, the canonical name of M consists of the canonical name of C, followed by ".", followed by the simple name of M. For every package, top level class, top level interface and primitive type, the canonical name is the same as the fully qualified name. The canonical name of an array type is defined only when the component type of the array has a canonical name. In that case, the canonical name of the array type consists of the canonical name of the component type of the array type followed by "[]".

The difference between a fully qualified name and a canonical name can be seen in examples such as:

package p;
class O1 { class I{}}
class O2 extends O1{};

In this example both p.O1.I and p.O2.I are fully qualified names that denote the same class, but only p.O1.I is its canonical name.

6.8 Naming Conventions

The class libraries of the Java platform attempt to use, whenever possible, names chosen according to the conventions presented here. These conventions help to make code more readable and avoid certain kinds of name conflicts.

We recommend these conventions for use in all programs written in the Java programming language. However, these conventions should not be followed slavishly if long-held conventional usage dictates otherwise. So, for example, the sin and cos methods of the class java.lang.Math have mathematically conventional names, even though these method names flout the convention suggested here because they are short and are not verbs.

6.8.1 Package Names

Names of packages that are to be made widely available should be formed as described in §7.7. Such names are always qualified names whose first identifier consists of two or three lowercase letters that name an Internet domain, such as com, edu, gov, mil, net, org, or a two-letter ISO country code such as uk or jp. Here are examples of hypothetical unique names that might be formed under this convention:

com.JavaSoft.jag.Oak
org.npr.pledge.driver
uk.ac.city.rugby.game

Names of packages intended only for local use should have a first identifier that begins with a lowercase letter, but that first identifier specifically should not be the identifier java; package names that start with the identifier java are reserved by Sun for naming Java platform packages.

When package names occur in expressions:

6.8.2 Class and Interface Type Names

Names of class types should be descriptive nouns or noun phrases, not overly long, in mixed case with the first letter of each word capitalized. For example:

ClassLoader
SecurityManager
Thread
Dictionary
BufferedInputStream
Likewise, names of interface types should be short and descriptive, not overly long, in mixed case with the first letter of each word capitalized. The name may be a descriptive noun or noun phrase, which is appropriate when an interface is used as if it were an abstract superclass, such as interfaces java.io.DataInput and java.io.DataOutput; or it may be an adjective describing a behavior, as for the interfaces Runnable and Cloneable.

Obscuring involving class and interface type names is rare. Names of fields, parameters, and local variables normally do not obscure type names because they conventionally begin with a lowercase letter whereas type names conventionally begin with an uppercase letter.

6.8.3 Method Names

Method names should be verbs or verb phrases, in mixed case, with the first letter lowercase and the first letter of any subsequent words capitalized. Here are some additional specific conventions for method names:

Whenever possible and appropriate, basing the names of methods in a new class on names in an existing class that is similar, especially a class from the Java Application Programming Interface classes, will make it easier to use.

Method names cannot obscure or be obscured by other names (§6.5.7).

6.8.4 Field Names

Names of fields that are not final should be in mixed case with a lowercase first letter and the first letters of subsequent words capitalized. Note that well-designed classes have very few public or protected fields, except for fields that are constants (final static fields) (§6.8.5).

Fields should have names that are nouns, noun phrases, or abbreviations for nouns. Examples of this convention are the fields buf, pos, and count of the class java.io.ByteArrayInputStream and the field bytesTransferred of the class java.io.InterruptedIOException.

Obscuring involving field names is rare.

6.8.5 Constant Names

The names of constants in interface types should be, and final variables of class types may conventionally be, a sequence of one or more words, acronyms, or abbreviations, all uppercase, with components separated by underscore "_" characters. Constant names should be descriptive and not unnecessarily abbreviated. Conventionally they may be any appropriate part of speech. Examples of names for constants include MIN_VALUE, MAX_VALUE, MIN_RADIX, and MAX_RADIX of the class Character.

A group of constants that represent alternative values of a set, or, less frequently, masking bits in an integer value, are sometimes usefully specified with a common acronym as a name prefix, as in:

interface ProcessStates {
	int PS_RUNNING = 0;
	int PS_SUSPENDED = 1;
}
Obscuring involving constant names is rare:

6.8.6 Local Variable and Parameter Names

Local variable and parameter names should be short, yet meaningful. They are often short sequences of lowercase letters that are not words. For example:

One-character local variable or parameter names should be avoided, except for temporary and looping variables, or where a variable holds an undistinguished value of a type. Conventional one-character names are:

Local variable or parameter names that consist of only two or three lowercase letters should not conflict with the initial country codes and domain names that are the first component of unique package names (§7.7).


Contents | Prev | Next | Index Java Language Specification
Second Edition
Copyright © 2000 Sun Microsystems, Inc. All rights reserved
Please send any comments or corrections to jls@java.sun.com