A class declaration specifies a new reference type:
ClassDeclaration:
ClassModifiersoptclass
IdentifierSuperopt
Interfacesopt
ClassBody
If a class is declared in a named package (§7.4.1) with fully qualified name P
(§6.7), then the class has the fully qualified name P.
Identifier. If the class is in an
unnamed package (§7.4.2), then the class has the fully qualified name Identifier.
In the example:
class Point { int x, y; }
the class Point
is declared in a compilation unit with no package
statement, and
thus Point
is its fully qualified name, whereas in the example:
package vista; class Point { int x, y; }
the fully qualified name of the class Point
is vista.Point
. (The package name
vista
is suitable for local or personal use; if the package were intended to be
widely distributed, it would be better to give it a unique package name (§7.7).)
A compile-time error occurs if the Identifier naming a class appears as the name of any other class type or interface type declared in the same package (§7.6).
A compile-time error occurs if the Identifier naming a class is also declared as a type by a single-type-import declaration (§7.5.1) in the compilation unit (§7.3) containing the class declaration.
package test;
import java.util.Vector;
class Point { int x, y; }
interface Point { // compile-time error #1 int getR(); int getTheta(); }
class Vector { Point[] pts; } // compile-time error #2
the first compile-time error is caused by the duplicate declaration of the name
Point
as both a class
and an interface
in the same package. A second error
detected at compile time is the attempt to declare the name Vector
both by a class
type declaration and by a single-type-import declaration.
Note, however, that it is not an error for the Identifier that names a class also to name a type that otherwise might be imported by a type-import-on-demand declaration (§7.5.2) in the compilation unit (§7.3) containing the class declaration. In the example:
package test;
import java.util.*;
class Vector { Point[] pts; } // not a compile-time error
the declaration of the class Vector
is permitted even though there is also a class
java.util.Vector
. Within this compilation unit, the simple name Vector
refers
to the class test.Vector
, not to java.util.Vector
(which can still be referred
to by code within the compilation unit, but only by its fully qualified name).