This document describes changes to the Java Language Specification to clarify the usage of terms and taxonomies related to classes and interfaces, and more clearly distinguish classes and interfaces from types.
The following terminology is preferred: a class declaration or an interface declaration is a syntactic structure that introduces a class or an interface, respectively. Various class and interface declarations have different syntactic forms, and can appear in different contexts, per the grammar. An enum declaration introduces a special kind of class, an enum class. An annotation declaration introduces a special kind of interface, an annotation interface.
A class type or an interface type is the type of a variable or an expression, where the type names a class or interface. The word type should be avoided when talking about a class or interface itself, or its declaration. For example, "member type" is not appropriate. (As an exception, we continue to use type name to describe a name that refers to a class, interface, or type parameter.)
Each class has a direct superclass type and direct superinterface types. These can be mapped to a direct superclass and direct superinterfaces when the extra information supplied by types (e.g., type arguments) is irrelevant. Through transitive closure, we can talk more generally about superclass types, superinterface types, superclasses, and superinterfaces.
Changes are described with respect to existing sections of the Java Language Specification. New text is indicated like this and deleted text is indicated like this. Explanation and discussion, as needed, is set aside in grey boxes.
Chapter 1: Introduction
1.1 Organization of the Specification
Chapter 2 describes grammars and the notation used to present the lexical and syntactic grammars for the language.
Chapter 3 describes the lexical structure of the Java programming language, which is based on C and C++. The language is written in the Unicode character set. It supports the writing of Unicode characters on systems that support only ASCII.
Chapter 4 describes types, values, and variables. Types are subdivided into primitive types and reference types.
The primitive types are defined to be the same on all machines and in all implementations, and are various sizes of two's-complement integers, single- and double-precision IEEE 754 standard floating-point numbers, a boolean
type, and a Unicode character char
type. Values of the primitive types do not share state.
Reference types are the class types, the interface types, and the array types. The reference types are implemented by dynamically created objects that are either instances of classes or arrays. Many references to each object can exist. All objects (including arrays) support the methods of the class Object
, which is the (single) root of the class hierarchy. A predefined String
class supports Unicode character strings. Classes exist for wrapping primitive values inside of objects. In many cases, wrapping and unwrapping is performed automatically by the compiler (in which case, wrapping is called boxing, and unwrapping is called unboxing). Class and interface declarations Classes and interfaces may be generic, that is, they may be parameterized by other reference types. Such declarations Parameterized types of such classes and interfaces may then be invoked with provide specific type arguments.
Variables are typed storage locations. A variable of a primitive type holds a value of that exact primitive type. A variable of a class type can hold a null reference or a reference to an object whose type is that class type that is an instance of the named class or any subclass of that class type. A variable of an interface type can hold a null reference or a reference to an instance of any class that implements the named interface. A variable of an array type can hold a null reference or a reference to an array. A variable of class type Object
can hold a null reference or a reference to any object, whether class instance or array.
Chapter 5 describes conversions and numeric promotions. Conversions change the compile-time type and, sometimes, the value of an expression. These conversions include the boxing and unboxing conversions between primitive types and reference types. Numeric promotions are used to convert the operands of a numeric operator to a common type where an operation can be performed. There are no loopholes in the language; casts on reference types are checked at run time to ensure type safety.
Chapter 6 describes declarations and names, and how to determine what names mean (that is, which declaration a name denotes). The Java programming language does not require classes and interfaces, or their members, to be declared before they are used. Declaration order is significant only for local variables, local classes, and the order of field initializers in a class or interface. Recommended naming conventions that make for more readable programs are described here.
Chapter 7 describes the structure of a program, which is organized into packages. The members of a package are classes, interfaces, and subpackages. Packages, and consequently their members, have names in a hierarchical name space; the Internet domain name system can usually be used to form unique package names. Compilation units contain declarations of the classes and interfaces that are members of a given package, and may import classes and interfaces from other packages to give them short names.
Packages may be grouped into modules that serve as building blocks in the construction of very large programs. The declaration of a module specifies which other modules (and thus packages, and thus classes and interfaces) are required in order to compile and run code in its own packages.
The Java programming language supports limitations on external access to the members of packages, classes, and interfaces. The members of a package may be accessible solely by other members in the same package, or by members in other packages of the same module, or by members of packages in different modules. Similar constraints apply to the members of classes and interfaces.
Chapter 8 describes classes. The members of classes are classes, interfaces, fields (variables) and methods. Class variables exist once per class. Class methods operate without reference to a specific object. Instance variables are dynamically created in objects that are instances of classes. Instance methods are invoked on instances of classes; such instances become the current object this
during their execution, supporting the object-oriented programming style.
Classes support single inheritance, in which each class has a single superclass. Each class inherits members from its superclass, and ultimately from the class Object
. Variables of a class type can reference an instance of that the named class or of any subclass of that class, allowing new types classes to be used with existing methods, polymorphically.
Classes support concurrent programming with synchronized
methods. Methods declare the checked exceptions that can arise from their execution, which allows compile-time checking to ensure that exceptional conditions are handled. Objects can declare a finalize
method that will be invoked before the objects are discarded by the garbage collector, allowing the objects to clean up their state.
For simplicity, the language has neither declaration "headers" separate from the implementation of a class nor separate type and class hierarchies.
A special form of classes, enums enum classes, support the definition of small sets of values and their manipulation in a type safe manner. Unlike enumerations in other languages, enums enum constants are objects and may have their own methods.
Chapter 9 describes interfaces. The members of interfaces are classes, interfaces, constant fields, and methods. Classes that are otherwise unrelated can implement the same interface. A variable of an interface type can contain a reference to any object that implements the interface.
Classes and interfaces support multiple inheritance from interfaces. A class that implements one or more interfaces may inherit instance methods from both its superclass and its superinterfaces.
Annotation types interfaces are specialized interfaces used to annotate declarations. Such annotations are not permitted to affect the semantics of programs in the Java programming language in any way. However, they provide useful input to various tools.
Chapter 10 describes arrays. Array accesses include bounds checking. Arrays are dynamically created objects and may be assigned to variables of type Object
. The language supports arrays of arrays, rather than multidimensional arrays.
Chapter 11 describes exceptions, which are nonresuming and fully integrated with the language semantics and concurrency mechanisms. There are three kinds of exceptions: checked exceptions, run-time exceptions, and errors. The compiler ensures that checked exceptions are properly handled by requiring that a method or constructor can result in a checked exception only if the method or constructor declares it. This provides compile-time checking that exception handlers exist, and aids programming in the large. Most user-defined exceptions should be checked exceptions. Invalid operations in the program detected by the Java Virtual Machine result in run-time exceptions, such as NullPointerException
. Errors result from failures detected by the Java Virtual Machine, such as OutOfMemoryError
. Most simple programs do not try to handle errors.
Chapter 12 describes activities that occur during execution of a program. A program is normally stored as binary files representing compiled classes and interfaces. These binary files can be loaded into a Java Virtual Machine, linked to other classes and interfaces, and initialized.
After initialization, class methods and class variables may be used. Some classes may be instantiated to create new objects of the class type. Objects that are class instances also contain an instance of each superclass of the class, and object creation involves recursive creation of these superclass instances.
When an object is no longer referenced, it may be reclaimed by the garbage collector. If an object declares a finalizer, the finalizer is executed before the object is reclaimed to give the object a last chance to clean up resources that would not otherwise be released. When a class is no longer needed, it may be unloaded.
Chapter 13 describes binary compatibility, specifying the impact of changes to types classes and interfaces on other types classes and interfaces that use the changed types classes and interfaces but have not been recompiled. These considerations are of interest to developers of types classes and interfaces that are to be widely distributed, in a continuing series of versions, often through the Internet. Good program development environments automatically recompile dependent code whenever a type class or interface is changed, so most programmers need not be concerned about these details.
Chapter 14 describes blocks and statements, which are based on C and C++. The language has no goto
statement, but includes labeled break
and continue
statements. Unlike C, the Java programming language requires boolean
(or Boolean
) expressions in control-flow statements, and does not convert types to boolean
implicitly (except through unboxing), in the hope of catching more errors at compile time. A synchronized
statement provides basic object-level monitor locking. A try
statement can include catch
and finally
clauses to protect against non-local control transfers.
Chapter 15 describes expressions. This document fully specifies the (apparent) order of evaluation of expressions, for increased determinism and portability. Overloaded methods and constructors are resolved at compile time by picking the most specific method or constructor from those which are applicable.
Chapter 16 describes the precise way in which the language ensures that local variables are definitely set before use. While all other variables are automatically initialized to a default value, the Java programming language does not automatically initialize local variables in order to avoid masking programming errors.
Chapter 17 describes the semantics of threads and locks, which are based on the monitor-based concurrency originally introduced with the Mesa programming language. The Java programming language specifies a memory model for shared-memory multiprocessors that supports high-performance implementations.
Chapter 18 describes a variety of type inference algorithms used to test applicability of generic methods and to infer types in a generic method invocation.
Chapter 19 presents a syntactic grammar for the language.
Chapter 2: Grammars
2.4 Grammar Notation
...
A very long right-hand side may be continued on a second line by clearly indenting the second line.
For example, the syntactic grammar contains this production:
- NormalClassDeclaration:
- {ClassModifier}
class
TypeIdentifier [TypeParameters]
[SuperclassClassExtends] [SuperinterfacesClassImplements] ClassBodywhich defines one right-hand side for the nonterminal NormalClassDeclaration.
Reflects the changes in 8.1.
...
Chapter 4: Types, Values, and Variables
4.5 Parameterized Types
A class or interface declaration that is generic (8.1.2, 9.1.2) defines a set of parameterized types.
A parameterized type is a class or interface type of the form C<
T1,...,Tn>
, where C is the name of a generic type class or interface and <
T1,...,Tn>
is a list of type arguments that denote a particular parameterization of the generic type class or interface.
A generic type class or interface has type parameters F1,...,Fn with corresponding bounds B1,...,Bn. Each type argument Ti of a parameterized type ranges over all types that are subtypes of all types listed in the corresponding bound. That is, for each bound type S in Bi, Ti is a subtype of S[F1:=T1,...,Fn:=Tn]
(4.10).
A parameterized type C<
T1,...,Tn>
is well-formed if all of the following are true:
C is the name of a generic
typeclass or interface.The number of type arguments is the same as the number of type parameters in the generic declaration of C.
When subjected to capture conversion (5.1.10) resulting in the type C
<
X1,...,Xn>
, each type argument Xi is a subtype of S[F1:=X1,...,Fn:=Xn]
for each bound type S in Bi.
It is a compile-time error if a parameterized type is not well-formed.
In this specification, whenever we speak of a class or interface type, we include the generic version parameterized types as well, unless explicitly excluded.
Two parameterized types are provably distinct if either of the following is true:
They are parameterizations of distinct generic type declarations.
Any of their type arguments are provably distinct.
Given the generic
typesclasses in the examples of 8.1.2, here are some well-formed parameterized types:
Seq<String>
Seq<Seq<String>>
Seq<String>.Zipper<Integer>
Pair<String,Integer>
Here are some incorrect parameterizations of those generic
typesclasses:
Seq<int>
is illegal, as primitive types cannot be type arguments.
Pair<String>
is illegal, as there are not enough type arguments.
Pair<String,String,String>
is illegal, as there are too many type arguments.
A parameterized type may be
ana parameterization of a generic class or interface which is nested. For example, if a non-generic class C has a generic member class D with type parameters<
T>
, then C.
D<Object>
is a parameterized type. And if a generic class C with type parameters<
T>
has a non-generic member class D, then the member class type C<String>.
D is a parameterized type, even though the class D is not generic.
4.5.2 Members and Constructors of Parameterized Types
Let C be a generic class or interface declaration with type parameters A1,...,An, and let C<
T1,...,Tn>
be a parameterization of C where, for 1 ≤ i ≤ n, Ti is a type (rather than a wildcard). Then:
Let m be a member or constructor declaration in C, whose type as declared is T (8.2, 8.8.6).
The type of m in C
<
T1,...,Tn>
is T[A1:=T1,...,An:=Tn]
.Let m be a member or constructor declaration in D, where D is a class extended by C or an interface implemented by C. Let D
<
U1,...,Uk>
be the supertype (4.10.2) of C<
T1,...,Tn>
that corresponds to D.The type of m in C
<
T1,...,Tn>
is the type of m in D<
U1,...,Uk>
.
If any of the type arguments in the parameterization of C are wildcards, then:
The types of the fields, methods, and constructors in C
<
T1,...,Tn>
are the types of the fields, methods, and constructors in the capture conversion of C<
T1,...,Tn>
(5.1.10).Let D be a (possibly generic) class or interface declaration in C. Then the type of D in C
<
T1,...,Tn>
is D where, if D is generic, all type arguments are unbounded wildcards.
This is of no consequence, as it is impossible to access a member of a parameterized type without performing capture conversion, and it is impossible to use a wildcard after the keyword
new
in a class instance creation expression (15.9).
The sole exception to the previous paragraph is when a nested parameterized type is used as the expression in an
instanceof
operator (15.20.2), where capture conversion is not applied.
A static
member that is declared in a generic type declaration class or interface must be referred to using the non-generic type that corresponds to the generic type name of the generic class or interface (6.1, 6.5.5.2, 6.5.6.2), or a compile-time error occurs.
In other words, it is illegal to refer to a
static
member declared in a generic type declaration by using a parameterized type.
4.8 Raw Types
To facilitate interfacing with non-generic legacy code, it is possible to use as a type the erasure (4.6) of a parameterized type (4.5) or the erasure of an array type (10.1) whose element type is a parameterized type. Such a type is called a raw type.
More precisely, a raw type is defined to be one of:
The reference type that is formed by taking the name of a generic
typeclass or interface declaration without an accompanying type argument list.An array type whose element type is a raw type.
A non-The name of an inner member class of a raw type R that is not inherited from a superclass or superinterface of R.static
member type
A The type of a non-generic class or interface type is not a raw type.
To see why
a non-the name of an inner member class of a raw type is considered raw, consider the following example:static
type memberclass Outer<T>{ T t; class Inner { T setOuterT(T t1) { t = t1; return t; } } }
The type of the member(s) of
Inner
depends on the type parameter ofOuter
. IfOuter
is raw,Inner
must be treated as raw as well, as there is no valid binding forT
.This rule applies only to
type membersinner member classes that are not inherited. Inheritedtype membersinner member classes that depend on type variables will be inherited as raw types as a consequence of the rule that the supertypes of a raw type are erased, described later in this section.Another implication of the rules above is that a generic inner class of a raw type can itself only be used as a raw type:
class Outer<T>{ class Inner<S> { S s; } }
It is not possible to access
Inner
as a partially raw type (a "rare" type):Outer.Inner<Double> x = null; // illegal Double d = x.s;
because
Outer
itself is raw, hence so are all its inner classes includingInner
, and so it is not possible to pass any type arguments to Inner.
The superclasses superclass types (respectively, superinterfaces superinterface types) of a raw type are the erasures of the superclasses superclass types (superinterfaces superinterface types) of any of the parameterizations of the generic type the named class or interface.
The type of a constructor (8.8), instance method (8.4, 9.4), or non-static
field (8.3) of a raw type C that is not inherited from its superclasses or superinterfaces is the erasure of its type in the generic declaration corresponding to class or interface C.
The type of an inherited instance method or non-static
field of a raw type C, where the member was declared in a class or interface D, is the type of the member in the supertype of C that names D.
Class inheritance is defined in 8.4.8, but we still need to explain the types of inherited members when accessed via a raw type. Simply saying that the supertypes of the raw type are erased isn't enough.
The type of a static
method or static
field of a raw type C is the same as its type in the generic declaration corresponding to class or interface C.
It is a compile-time error to pass type arguments to a non-static
type member class or interface of a raw type that is not inherited from its superclasses or superinterfaces.
It is a compile-time error to attempt to use a type member class or interface of a parameterized type as a raw type.
This means that the ban on "rare" types extends to the case where the qualifying type is parameterized, but we attempt to use the inner class as a raw type:
Outer<Integer>.Inner x = null; // illegal
This is the opposite of the case discussed above. There is no practical justification for this half-baked type. In legacy code, no type arguments are used. In non-legacy code, we should use the generic types correctly and pass all the required type arguments.
The supertype of a class may be a raw type. Member accesses for the class are treated as normal, and member accesses for the supertype are treated as for raw types. In the constructor of the class, calls to super
are treated as method calls on a raw type.
This is covered in the treatment of superclasses and inheritance elsewhere—see, e.g., 8.1.4, 8.3, and 8.4.8.
The use of raw types is allowed only as a concession to compatibility of legacy code. The use of raw types in code written after the introduction of generics into the Java programming language is strongly discouraged. It is possible that future versions of the Java programming language will disallow the use of raw types.
To make sure that potential violations of the typing rules are always flagged, some accesses to members of a raw type will result in compile-time unchecked warnings. The rules for compile-time unchecked warnings when accessing members or constructors of raw types are as follows:
At an assignment to a field: if the type of the Primary in the field access expression (15.11) is a raw type, then a compile-time unchecked warning occurs if erasure changes the field's type.
At an invocation of a method or constructor: if the type of the class or interface to search (15.12.1) is a raw type, then a compile-time unchecked warning occurs if erasure changes any of the formal parameter types of the method or constructor.
No compile-time unchecked warning occurs for a method call when the formal parameter types do not change under erasure (even if the return type and/or
throws
clause changes), for reading from a field, or for a class instance creation of a raw type.
...
4.9 Intersection Types
An intersection type takes the form T1 &
... &
Tn (n > 0), where Ti (1 ≤ i ≤ n) are types.
Intersection types can be derived from type parameter bounds (4.4) and cast expressions (15.16); they also arise in the processes of capture conversion (5.1.10) and least upper bound computation (4.10.4).
The values of an intersection type are those objects that are values of all of the types Ti for 1 ≤ i ≤ n.
Every intersection type T1 &
... &
Tn induces a notional class or interface for the purpose of identifying the members of the intersection type, as follows:
For each Ti (1 ≤ i ≤ n), let Ci be the most specific class or array type such that Ti
<:
Ci. Then there must be some Ck such that Ck<:
Ci for any i (1 ≤ i ≤ n), or a compile-time error occurs.For 1 ≤ j ≤ n, if Tj is a type variable, then let Tj' be an interface whose members are the same as the
public
members of Tj; otherwise, if Tj is an interface, then let Tj' be Tj.If Ck is
Object
, a notional interface is induced; otherwise, a notional class is induced with direct superclass type Ck. This class or interface has directsuperinterfacessuperinterface types T1', ..., Tn' and is declared in the package in which the intersection type appears.
The members of an intersection type are the members of the class or interface it induces.
It is worth dwelling upon the distinction between intersection types and the bounds of type variables. Every type variable bound induces an intersection type. This intersection type is often trivial, consisting of a single type. The form of a bound is restricted (only the first element may be a class or type variable, and only one type variable may appear in the bound) to preclude certain awkward situations coming into existence. However, capture conversion can lead to the creation of type variables whose bounds are more general, such as array types).
4.10 Subtyping
4.10.2 Subtyping among Class and Interface Types
Given a non-generic type declaration class or interface C, the direct supertypes of the type of C are all of the following:
The direct superclass type of C (8.1.4), if C is a class.
The direct
superinterfacessuperinterface types of C (8.1.5, 9.1.3).The type
Object
, if C is an interfacetypewith no directsuperinterfacessuperinterface types (9.1.3).
Given a generic type declaration class or interface C with type parameters <
F1,...,Fn>
(n > 0), the direct supertypes of the raw type C (4.8) are all of the following:
The erasure (4.6) of the direct superclass type of
the raw typeC, if C is a class.The erasure of the direct
superinterfacessuperinterface types ofthe raw typeC.The type
Object
, if Cis<
F1,...,Fn>
a generic interface typean interface with no directsuperinterfaces (9.1.2)superinterface types.
Given a generic type declaration C<
F1,...,Fn>
(n > 0), the direct supertypes of the generic type C<
F1,...,Fn>
are all of the following:
The direct superclass of C
<
F1,...,Fn>
.The direct superinterfaces of C
<
F1,...,Fn>
.The type
Object
, if C<
F1,...,Fn>
is a generic interface type with no direct superinterfaces.The raw type C.
A generic type is not a distinct kind of type. The generic class has supertypes, as described in 8.1.4 and 8.1.5. A parameterized type has supertypes, as described below.
Given a generic type declaration class or interface C with type parameters <
F1,...,Fn>
(n > 0), the direct supertypes of the parameterized type C<
T1,...,Tn>
, where each of Ti (1 ≤ i ≤ n) is a type, are all of the following:
D<
U1 θ,...,Uk θ>
, where D<
U1,...,Uk>
is a generic type which is a direct supertype of the generic type C<
F1,...,Fn>
and θ is the substitution[F1:=T1,...,Fn:=Tn]
.The substitution
[F1:=T1,...,Fn:=Tn]
applied to the direct superclass type of C, if C is a class.The substitution
[F1:=T1,...,Fn:=Tn]
applied to the direct superinterface types of C.C
<
S1,...,Sn>
, where Si contains Ti (1 ≤ i ≤ n) (4.5.1).The type
Object
, if C<F1,...,Fn>isa generic interface typean interface with no directsuperinterfacessuperinterface types.The raw type C.
Given a generic type declaration class or interface C with type parameters <
F1,...,Fn>
(n > 0), the direct supertypes of the parameterized type C<
R1,...,Rn>
where at least one of the Ri (1 ≤ i ≤ n) is a wildcard type argument, are the direct supertypes of the parameterized type C<
X1,...,Xn>
which is the result of applying capture conversion to C<
R1,...,Rn>
(5.1.10).
The direct supertypes of an intersection type T1 &
... &
Tn are Ti (1 ≤ i ≤ n).
The direct supertypes of a type variable are the types listed in its bound.
A type variable is a direct supertype of its lower bound.
The direct supertypes of the null type are all reference types other than the null type itself.
4.11 Where Types Are Used
Types are used in most kinds of declaration and in certain kinds of expression. Specifically, there are 16 type contexts where types are used:
In declarations:
A type in the
extends
orimplements
clause of a class declaration (8.1.4, 8.1.5, 8.5, 9.5)A type in the
extends
clause of an interface declaration (9.1.3, 8.5, 9.5)The return type of a method (including the type of an element of an annotation
typeinterface) (8.4.5, 9.4, 9.6.1)A type in the
throws
clause of a method or constructor (8.4.6, 8.8.5, 9.4)A type in the
extends
clause of a type parameter declaration of a generic class, interface, method, or constructor (8.1.2, 9.1.2, 8.4.4, 8.8.4)The type in a field declaration of a class or interface (including an enum constant) (8.3, 9.3, 8.9.1)
The type in a formal parameter declaration of a method, constructor, or lambda expression (8.4.1, 8.8.1, 9.4, 15.27.1)
The type of the receiver parameter of a method (8.4)
The type in a local variable declaration (14.4, 14.14.1, 14.14.2, 14.20.3)
The type in an exception parameter declaration (14.20)
In expressions:
A type in the explicit type argument list to an explicit constructor invocation statement,
orclass instance creation expression,ormethod invocation expression, or method reference expression (8.8.7.1, 15.9, 15.12, 15.13)In an unqualified class instance creation expression, as the class type to be instantiated (15.9) or as the direct superclass type or direct superinterface type of an anonymous class to be instantiated (15.9.5)
The element type in an array creation expression (15.10.1)
The type in the cast operator of a cast expression (15.16)
The type that follows the
instanceof
relational operator (15.20.2)In a method reference expression (15.13), as the reference type to search for a member method or as the class type or array type to construct.
Also, types are used as:
The element type of an array type in any of the above contexts; and
A non-wildcard type argument, or a bound of a wildcard type argument, of a parameterized type in any of the above contexts.
Finally, there are three two special terms in the Java programming language which denote the use of a type:
An unbounded wildcard (4.5.1)
The
...
in the type of a variable arity parameter (8.4.1), to indicate an array typeThe simple name of a type in a constructor declaration (8.8), to indicate the class of the constructed objectThe identifier used in a constructor declaration is a class name, not a type.
The meaning of types in type contexts is given by:
4.2, for primitive types
4.4, for type parameters
4.5, for class and interface types that are parameterized, or appear either as type arguments in a parameterized type or as bounds of wildcard type arguments in a parameterized type
4.8, for class and interface types that are raw
4.9, for intersection types in the bounds of type parameters
6.5, for
class and interfacetypes of non-generic classes and interfacesin contexts where genericity is unimportant (6.1)and type variables10.1, for array types
Some type contexts restrict how a reference type may be parameterized:
The following type contexts require that if a type is a parameterized reference type, it has no wildcard type arguments:
In an
extends
orimplements
clause of a class declaration (8.1.4, 8.1.5)In an
extends
clause of an interface declaration (9.1.3)In an unqualified class instance creation expression, as the class type to be instantiated (15.9) or as the direct superclass type or direct superinterface type of an anonymous class to be instantiated (15.9.5)
In a method reference expression (15.13), as the reference type to search for a member method or as the class type or array type to construct.
In addition, no wildcard type arguments are permitted in the explicit type argument list to an explicit constructor invocation statement or class instance creation expression or method invocation expression or method reference expression (8.8.7.1, 15.9, 15.12, 15.13).
The following type contexts require that if a type is a parameterized reference type, it has only unbounded wildcard type arguments (i.e. it is a reifiable type) :
The following type contexts disallow a parameterized reference type altogether, because they involve exceptions and the type of an exception is non-generic (6.1):
In any type context where a type is used, it is possible to annotate the keyword denoting a primitive type or the Identifier denoting the simple name of a reference type. It is also possible to annotate an array type by writing an annotation to the left of the
[
at the desired level of nesting in the array type. Annotations in these locations are called type annotations, and are specified in 9.7.4. Here are some examples:
@Foo int[] f;
annotates the primitive typeint
int @Foo [] f;
annotates the array typeint[]
int @Foo [][] f;
annotates the array typeint[][]
int[] @Foo [] f;
annotates the array typeint[]
which is the component type of the array typeint[][]
Five of the type contexts which appear in declarations occupy the same syntactic real estate as a number of declaration contexts (9.6.4.1):
The return type of a method (including the type of an element of an annotation
typeinterface)The type in a field declaration of a class or interface (including an enum constant)
The type in a formal parameter declaration of a method, constructor, or lambda expression
The type in a local variable declaration
The type in an exception parameter declaration
The fact that the same syntactic location in a program can be both a type context and a declaration context arises because the modifiers for a declaration immediately precede the type of the declared entity. 9.7.4 explains how an annotation in such a location is deemed to appear in a type context or a declaration context or both.
Example 4.11-1. Usage of a Type
import java.util.Random;
import java.util.Collection;
import java.util.ArrayList;
class MiscMath<T extends Number> {
int divisor;
MiscMath(int divisor) { this.divisor = divisor; }
float ratio(long l) {
try {
l /= divisor;
} catch (Exception e) {
if (e instanceof ArithmeticException)
l = Long.MAX_VALUE;
else
l = 0;
}
return (float)l;
}
double gausser() {
Random r = new Random();
double[] val = new double[2];
val[0] = r.nextGaussian();
val[1] = r.nextGaussian();
return (val[0] + val[1]) / 2;
}
Collection<Number> fromArray(Number[] na) {
Collection<Number> cn = new ArrayList<Number>();
for (Number n : na) cn.add(n);
return cn;
}
<S> void loop(S s) { this.<S>loop(s); }
}
In this example, types are used in declarations of the following:
Imported types (7.5); here the typeRandom
, imported from the typejava.util.Random
of the packagejava.util
, is declaredClasses and interfaces, not types, are imported.
Fields, which are the class variables and instance variables of classes (8.3), and constants of interfaces (9.3); here the field
divisor
in the classMiscMath
is declared to be of typeint
Method parameters (8.4.1); here the parameter
l
of the methodratio
is declared to be of typelong
Method results (8.4); here the result of the method
ratio
is declared to be of typefloat
, and the result of the methodgausser
is declared to be of typedouble
Constructor parameters (8.8.1); here the parameter of the constructor for
MiscMath
is declared to be of typeint
Local variables (14.4, 14.14); the local variables
r
andval
of the methodgausser
are declared to be of typesRandom
anddouble[]
(array ofdouble
)Exception parameters (14.20); here the exception parameter
e
of thecatch
clause is declared to be of typeException
Type parameters (4.4); here the type parameter of
MiscMath
is a type variableT
with the typeNumber
as its declared boundIn any declaration that uses a parameterized type; here the type
Number
is used as a type argument (4.5.1) in the parameterized typeCollection<Number>
.
and in expressions of the following kinds:
Class instance creations (15.9); here a local variable
r
of methodgausser
is initialized by a class instance creation expression that uses the typeRandom
Generic class (8.1.2) instance creations (15.9); here
Number
is used as a type argument in the expressionnew ArrayList<Number>()
Array creations (15.10.1); here the local variable
val
of methodgausser
is initialized by an array creation expression that creates an array ofdouble
with size 2Generic method (8.4.4) or constructor (8.8.4) invocations (15.12); here the method
loop
calls itself with an explicit type argumentS
Casts (15.16); here the
return
statement of the methodratio
uses thefloat
type in a castThe
instanceof
operator (15.20.2); here theinstanceof
operator tests whethere
is assignment-compatible with the typeArithmeticException
Chapter 6: Names
Names are used to refer to entities declared in a program.
A declared entity (6.1) is a package, class type (normal or enum), interface type (normal or annotation type), member (class, interface, field, or method) of a reference type, type parameter (of a class, interface, method or constructor), parameter (to a method, constructor, or exception handler) formal parameter, exception parameter, or local variable.
There's a whole section coming up (6.1) dedicated to enumerating all the cases. The introductory sentence for the chapter shouldn't be trying to repeat that entire enumeration. E.g., we can describe the different kinds of class declarations later.
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.
A qualified name N.x may be used to refer to a member of a package or reference type, 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. Access to a declared entity is also relevant in a field access expression (15.11), a method invocation expression in which the method is not specified by a simple name (15.12), a method reference expression (15.13), or a qualified class instance creation expression (15.9). In the absence of an access modifier, most declarations have package access, allowing access anywhere within the package that contains its declaration; other possibilities are public
, protected
, and private
.
Fully qualified and canonical names (6.7) are also discussed in this chapter.
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. The identifier is constrained to be a type identifier when the entity being introduced is a class, interface, or type parameter.
A declared entity is one of the following:
A module, declared in a
module
declaration (7.7)A package, declared in a
package
declaration (7.4)An imported
typeclass or interface, declared in a single-type-import declaration or a type-import-on-demand declaration (7.5.1, 7.5.2)An imported
static
member, declared in a single-static-import declaration or a static-import-on-demand declaration (7.5.3, 7.5.4)A class, declared
inby a normal classtypedeclaration (8.1) or an enum declaration (8.9)An interface, declared
in anby a normal interfacetypedeclaration (9.1) or an annotation declaration (9.6)A type parameter, declared as part of the declaration of a generic class, interface, method, or constructor (8.1.2, 9.1.2, 8.4.4, 8.8.4)
A member of a reference type (8.2, 9.2, 8.9.3, 9.6, 10.7), one of the following:
An enum constant (8.9)Enum constants are not members—they introduce implicit fields, which are members.
A field, one of the following:
A method, one of the following:
An enum constant (8.9.1)
A parameter, one of the following:A formal parameter of a method or constructor of a class type or enum type (8.4.1, 8.8.1, 8.9.2), or of a lambda expression (15.27.1)A formal parameter of anabstract
method of an interface type or annotation type (9.4, 9.6.1)An exception parameter of an exception handler declared in acatch
clause of atry
statement (14.20)
A formal parameter of a method of a class or interface (8.4.1), a constructor of a class (8.8.1), or a lambda expression (15.27.1)
An exception parameter of an exception handler declared in a
catch
clause of atry
statement (14.20)
Formal parameters and exception parameters are typically treated as two distinct entities. Formal parameters of class methods and interface methods, on the other hand, are specified in exactly one place, and don't need to be treated as distinct things.
A local variable, one of the following:
A local class (14.3)
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.
The declaration of a type which is not generic (class C ...
) declares one entity: a non-generic type (C
). A non-generic type is not a raw type, despite the syntactic similarity. In contrast, the declaration of a generic type (class C<T> ...
or interface C<T> ...
) declares two entities: a generic type (C<T>
) and a corresponding non-generic type (C
). In this case, the meaning of the term C
depends on the context where it appears:
If genericity is unimportant, as in the non-generic contexts identified below, the identifier
C
denotes the non-generic typeC
.If genericity is important, as in all contexts from 6.5 except the non-generic contexts, the identifier
C
denotes either:
The 14 non-generic contexts are as follows:
In a
uses
orprovides
directive in a module declaration (7.7.1)In a single-type-import declaration (7.5.1)
To the left of the
.
in a single-static-import declaration (7.5.3)To the left of the
.
in a static-import-on-demand declaration (7.5.4)To the left of the
(
in a constructor declaration (8.8)After the
@
sign in an annotation (9.7)To the left of
.class
in a class literal (15.8.2)To the left of
.this
in a qualifiedthis
expression (15.8.4)To the left of
.super
in a qualified superclass field access expression (15.11.2)To the left of
.
Identifier or.super.
Identifier in a qualified method invocation expression (15.12)To the left of
.super::
in a method reference expression (15.13)In a qualified expression name in a postfix expression or a
try
-with-resources statement (15.14.1, 14.20.3)In a
throws
clause of a method or constructor (8.4.6, 8.8.5, 9.4)In an exception parameter declaration (14.20)
The first eleven non-generic contexts correspond to the first eleven syntactic contexts for a TypeName in 6.5.1. The twelfth non-generic context is where a qualified ExpressionName such as C.x
may include a TypeName C
to denote static member access. The common use of TypeName in these twelve contexts is significant: it indicates that these contexts involve a less-than-first-class use of a type. In contrast, the thirteenth and fourteenth non-generic contexts employ ClassType, indicating that throws
and catch
clauses use types in a first-class way, in line with, say, field declarations. The characterization of these two contexts as non-generic is due to the fact that an exception type cannot be parameterized.
Note that the ClassType production allows annotations, so it is possible to annotate the use of a type in a
throws
orcatch
clause, whereas the TypeName production disallows annotations, so it is not possible to annotate the name of a type in, say, a single-type-import declaration.
The declaration of a generic class or interface (
class C<T> ...
orinterface C<T> ...
) (8.1.2, 9.1.2) introduces both a class namedC
and a family of types: rawC
,C<Foo>
,C<Bar>
, etc.When a reference to
C
occurs where genericity is unimportant, identified below as one of the non-generic contexts, the reference toC
denotes the class or interfaceC
. In other contexts, the reference toC
denotes a type, or part of a type, introduced byC
.The 14 non-generic contexts are as follows:
In a
uses
orprovides
directive in a module declaration (7.7.1)In a single-type-import declaration (7.5.1)
To the left of the
.
in a single-static-import declaration (7.5.3)To the left of the
.
in a static-import-on-demand declaration (7.5.4)To the left of the
(
in a constructor declaration (8.8)After the
@
sign in an annotation (9.7)To the left of
.class
in a class literal (15.8.2)To the left of
.this
in a qualifiedthis
expression (15.8.4)To the left of
.super
in a qualified superclass field access expression (15.11.2)To the left of
.
Identifier or.super.
Identifier in a qualified method invocation expression (15.12)To the left of
.super::
in a method reference expression (15.13)In a qualified expression name in a postfix expression or a
try
-with-resources statement (15.14.1, 14.20.3)In a
throws
clause of a method or constructor (8.4.6, 8.8.5, 9.4)In an exception parameter declaration (14.20)
The first eleven non-generic contexts correspond to the first eleven syntactic contexts for a TypeName in 6.5.1. The twelfth non-generic context is where a qualified ExpressionName such as
C.x
may include a TypeNameC
to denote static member access. The common use of TypeName in these twelve contexts is significant: it indicates that these contexts involve a less-than-first-class use of a type. In contrast, the thirteenth and fourteenth non-generic contexts employ ClassType, indicating thatthrows
andcatch
clauses use types in a first-class way, in line with, say, field declarations. The characterization of these two contexts as non-generic is due to the fact that an exception type cannot be parameterized.Note that the ClassType production allows annotations, so it is possible to annotate the use of a type in a
throws
orcatch
clause, whereas the TypeName production disallows annotations, so it is not possible to annotate the name of a type in, say, a single-type-import declaration.
This discussion was an earlier attempt to do what we're doing in this document in a more comprehensive way: distinguish between classes and (possibly parameterized) class types, and between interfaces and (possible parameterized) interface types. Now the terminology surrounding the above contexts (in their respective sections) should make clear that there is, for the most part, no type involved at all—these are constructs that talk about classes and interfaces, not their types.
The discussion is preserved here as a note, with some modifications to the introductory paragraphs, to help clarify the distinction between references to classes and references to types.
Naming Conventions
The class libraries of the Java SE Platform attempt to use, whenever possible, names chosen according to the conventions presented below. 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
andcos
methods of the classjava.lang.Math
have mathematically conventional names, even though these method names flout the convention suggested here because they are short and are not verbs.
...
Class and Interface
TypeNames
Names of
class typesclasses should be descriptive nouns or noun phrases, not overly long, in mixed case with the first letter of each word capitalized.
Example 6.1-3. Descriptive Class Names
`ClassLoader`
SecurityManager
`Thread`
Dictionary
BufferedInputStream
Likewise, names of
interface typesinterfaces 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 interfacesjava.io.DataInput
andjava.io.DataOutput
; or it may be an adjective describing a behavior, as for the interfacesRunnable
andCloneable
.
Type Variable Names
Type variable names should be pithy (single character if possible) yet evocative, and should not include lower case letters. This makes it easy to distinguish type parameters from ordinary classes and interfaces.
Container
typesclasses and interfaces should use the nameE
for their element type. Maps should useK
for the type of their keys andV
for the type of their values. The nameX
should be used for arbitrary exception types. We useT
for type, whenever there is not anything more specific about the type to distinguish it. (This is often the case in generic methods.)
If there are multiple type parameters that denote arbitrary types, one should use letters that neighbor
T
in the alphabet, such asS
. Alternately, it is acceptable to use numeric subscripts (e.g.,T1
,T2
) to distinguish among the different type variables. In such cases, all the variables with the same prefix should be subscripted.
If a generic method appears inside a generic class, it is a good idea to avoid using the same names for the type parameters of the method and class, to avoid confusion. The same applies to nested generic classes.
Example 6.1-4. Conventional Type Variable Names
public class HashSet<E> extends AbstractSet<E> { ... }
public class HashMap<K,V> extends AbstractMap<K,V> { ... }
public class ThreadLocal<T> { ... }
public interface Functor<T, X extends Throwable> {
T eval() throws X;
}
When type parameters do not fall conveniently into one of the categories mentioned, names should be chosen to be as meaningful as possible within the confines of a single letter. The names mentioned above (
E
,K
,V
,X
,T
) should not be used for type parameters that do not fall into the designated categories.
...
Constant Names
The names of constants in
interface typesinterfaces should be, andfinal
variables ofclass typesclasses 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
, andMAX_RADIX
of the classCharacter
.
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.
For example:
interface ProcessStates { int PS_RUNNING = 0; int PS_SUSPENDED = 1; }
...
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 class, interface, or type parameter (6.5.5), ; a variable or value in an expression (6.5.6), ; or a method (6.5.7).
Packages,
and reference typesclasses, interfaces, and type parameters have members which may be accessed by qualified names. As background for the discussion of qualified names and the determination of the meaning of names, see the descriptions of membership in 4.4, 4.5.2, 4.8, 4.9, 7.1, 8.2, 9.2, and 10.7.
Not all identifiers in a program are a part of a name. Identifiers are also used in the following situations:
In declarations (6.1), where an identifier may occur to specify the name by which the declared entity will be known.
As labels in labeled statements (14.7) and in
break
andcontinue
statements (14.15, 14.16) that refer to statement labels.The identifiers used in labeled statements and their associated
break
andcontinue
statements are completely separate from those used in declarations.In field access expressions (15.11), where an identifier occurs after a "
.
" token to indicate a member of the object denoted by the expression before the ".
" token, or the object denoted by thesuper
or TypeName.super
before the ".
" token.In some method invocation expressions (15.12), wherever an identifier occurs after a "
.
" token and before a "(
" token to indicate a method to be invoked for the object denoted by the expression before the ".
" token, or the type denoted by the TypeName before the ".
" token, or the object denoted by thesuper
or TypeName.super
before the ".
" token.In some method reference expressions (15.13), wherever an identifier occurs after a "
::
" token to indicate a method of the object denoted by the expression before the "::
" token, or the type denoted by the TypeName before the "::
" token, or the object denoted by thesuper
or TypeName.super
before the "::
" token.In qualified class instance creation expressions (15.9), where an identifier occurs to the right of the
new
token to indicate a type that is a member of the compile-time type of the expression preceding thenew
token.In element-value pairs of annotations (9.7.1), to denote an element of the corresponding annotation
typeinterface.
...
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 not shadowed (6.4.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 scope of the declaration of an observable top level package (7.4.3) is all observable compilation units associated with modules to which the package is uniquely visible (7.4.3).
The declaration of a package that is not observable is never in scope.
The declaration of a subpackage is never in scope.
The package java
is always in scope.
The scope of a type class or interface imported by a single-type-import declaration (7.5.1) or a type-import-on-demand declaration (7.5.2) is the module declaration (7.7) and all the class and interface type declarations (7.6) of the compilation unit in which the import
declaration appears, as well as any annotations on the module declaration or package declaration of the compilation unit.
The scope of a member imported by a single-static-import declaration (7.5.3) or a static-import-on-demand declaration (7.5.4) is the module declaration and all the class and interface type declarations of the compilation unit in which the import
declaration appears, as well as any annotations on the module declaration or package declaration of the compilation unit.
The scope of a top level type class or interface (7.6) is all type class and interface declarations in the package in which the top level type class or interface is declared.
The scope of a declaration of a member m declared in or inherited by a class type or interface C (8.1.6 8.2, 9.2) is the entire body of C, including any nested type class or interface declarations.
The scope of a declaration of a member m declared in or inherited by an interface type I (9.1.4) is the entire body of I, including any nested type declarations.
The scope of an enum constant C declared in an enum type T is the body of T, and any case
label of a switch
statement whose expression is of enum type T (14.11).
Names do not resolve to enum constants, they resolve to implicit fields of enum classes. Switch statements require some special treatment, but don't rely on the normal scoping/name resolution mechanisms.
The scope of a formal parameter of a method (8.4.1), constructor (8.8.1), or lambda expression (15.27) is the entire body of the method, constructor, or lambda expression.
The scope of a class's type parameter (8.1.2) is the type parameter section of the class declaration, the type parameter section of any superclass type or superinterface type of the class declaration, and the class body.
The scope of an interface's type parameter (9.1.2) is the type parameter section of the interface declaration, the type parameter section of any superinterface type of the interface declaration, and the interface body.
The scope of a method's type parameter (8.4.4) is the entire declaration of the method, including the type parameter section, but excluding the method modifiers.
The scope of a constructor's type parameter (8.8.4) is the entire declaration of the constructor, including the type parameter section, but excluding the constructor modifiers.
The scope of a local class declaration immediately enclosed by a block (14.2) is the rest of the immediately enclosing block, including its own class declaration.
The scope of a local class declaration immediately enclosed by a switch block statement group (14.11) is the rest of the immediately enclosing switch block statement group, including its own class declaration.
The scope of a local variable declaration in a block (14.4) is the rest of the block in which the declaration appears, starting with its own initializer and including any further declarators to the right in the local variable declaration statement.
The scope of a local variable declared in the ForInit part of a basic for
statement (14.14.1) includes all of the following:
Its own initializer
Any further declarators to the right in the ForInit part of the
for
statementThe Expression and ForUpdate parts of the
for
statementThe contained Statement
The scope of a local variable declared in the FormalParameter part of an enhanced for
statement (14.14.2) is the contained Statement.
The scope of a parameter of an exception handler that is declared in a catch
clause of a try
statement (14.20) is the entire block associated with the catch
.
The scope of a variable declared in the ResourceSpecification of a try
-with-resources statement (14.20.3) is from the declaration rightward over the remainder of the ResourceSpecification and the entire try
block associated with the try
-with-resources statement.
The translation of a
try
-with-resources statement implies the rule above.
Example 6.3-1. Scope of Type Class Declarations
These rules imply that declarations of class and interface types need not appear before uses of the types. In the following program, the use of PointList
in class Point
is valid, because the scope of the class declaration PointList
includes both class Point
and class PointList
, as well as any other type class or interface declarations in other compilation units of package points
.
package points;
class Point {
int x, y;
PointList list;
Point next;
}
class PointList {
Point first;
}
Example 6.3-2. Scope of Local Variable Declarations
The following program causes a compile-time error because the initialization of local variable x
is within the scope of the declaration of local variable x
, but the local variable x
does not yet have a value and cannot be used. The field x
has a value of 0
(assigned when Test1
was initialized) but is a red herring since it is shadowed (6.4.1) by the local variable x
.
class Test1 {
static int x;
public static void main(String[] args) {
int x = x;
}
}
The following program does compile:
class Test2 {
static int x;
public static void main(String[] args) {
int x = (x=2)*2;
System.out.println(x);
}
}
because the local variable x
is definitely assigned (16) before it is used. It prints:
4
In the following program, the initializer for three
can correctly refer to the variable two
declared in an earlier declarator, and the method invocation in the next line can correctly refer to the variable three
declared earlier in the block.
class Test3 {
public static void main(String[] args) {
System.out.print("2+1=");
int two = 2, three = two + 1;
System.out.println(three);
}
}
This program produces the output:
2+1=3
6.5 Determining the Meaning of a Name
6.5.1 Syntactic Classification of a Name According to Context
A name is syntactically classified as a ModuleName in these contexts:
In a
requires
directive in a module declaration (7.7.1)To the right of
to
in anexports
oropens
directive in a module declaration (7.7.2)
A name is syntactically classified as a PackageName in these contexts:
To the right of
exports
oropens
in a module declarationTo the left of the "
.
" in a qualified PackageName
A name is syntactically classified as a TypeName in these contexts:
The first eleven non-generic contexts (6.1)To name a class or interface:In a
uses
orprovides
directive in a module declaration (7.7.1)In a single-type-import declaration (7.5.1)
To the left of the
.
in a single-static-import declaration (7.5.3)To the left of the
.
in a static-import-on-demand declaration (7.5.4)To the left of the
(
in a constructor declaration (8.8)After the
@
sign in an annotation (9.7)To the left of
.class
in a class literal (15.8.2)To the left of
.this
in a qualifiedthis
expression (15.8.4)To the left of
.super
in a qualified superclass field access expression (15.11.2)To the left of
.
Identifier or.super.
Identifier in a qualified method invocation expression (15.12)To the left of
.super::
in a method reference expression (15.13)
As the Identifier or dotted Identifier sequence that constitutes any ReferenceType (including a ReferenceType to the left of the brackets in an array type, or to the left of the < in a parameterized type, or in a non-wildcard type argument of a parameterized type, or in an
extends
orsuper
clause of a wildcard type argument of a parameterized type) in the 16 contexts where types are used (4.11):In an
extends
orimplements
clause of a class declaration (8.1.4, 8.1.5, 8.5, 9.5)In an
extends
clause of an interface declaration (9.1.3)The return type of a method (8.4, 9.4) (including the type of an element of an annotation
typeinterface (9.6.1))In the
throws
clause of a method or constructor (8.4.6, 8.8.5, 9.4)In an
extends
clause of a type parameter declaration of a generic class, interface, method, or constructor (8.1.2, 9.1.2, 8.4.4, 8.8.4)The type in a field declaration of a class or interface (8.3, 9.3)
The type in a formal parameter declaration of a method, constructor, or lambda expression (8.4.1, 8.8.1, 9.4, 15.27.1)
The type of the receiver parameter of a method (8.4)
The type in a local variable declaration (14.4, 14.14.1, 14.14.2, 14.20.3)
A type in an exception parameter declaration (14.20)
In an explicit type argument list to an explicit constructor invocation statement or class instance creation expression or method invocation expression (8.8.7.1, 15.9, 15.12)
In an unqualified class instance creation expression, either as the class type to be instantiated (15.9) or as the direct superclass or direct superinterface of an anonymous class to be instantiated (15.9.5)
The element type in an array creation expression (15.10.1)
The type in the cast operator of a cast expression (15.16)
The type that follows the
instanceof
relational operator (15.20.2)In a method reference expression (15.13), as the reference type to search for a member method or as the class type or array type to construct.
The extraction of a TypeName from the identifiers of a ReferenceType in the 16 contexts above is intended to apply recursively to all sub-terms of the ReferenceType, such as its element type and any type arguments.
For example, suppose a field declaration uses the type
p.q.Foo[]
. The brackets of the array type are ignored, and the termp.q.Foo
is extracted as a dotted sequence of Identifiers to the left of the brackets in an array type, and classified as a TypeName. A later step determines which ofp
,q
, andFoo
is a type name or a package name.As another example, suppose a cast operator uses the type
p.q.Foo<? extends String>
. The termp.q.Foo
is again extracted as a dotted sequence of Identifier terms, this time to the left of the<
in a parameterized type, and classified as a TypeName. The termString
is extracted as an Identifier in anextends
clause of a wildcard type argument of a parameterized type, and classified as a TypeName.
A name is syntactically classified as an ExpressionName in these contexts:
As the qualifying expression in a qualified superclass constructor invocation (8.8.7.1)
As the qualifying expression in a qualified class instance creation expression (15.9)
As the array reference expression in an array access expression (15.10.3)
As a PostfixExpression (15.14)
As the left-hand operand of an assignment operator (15.26)
As a VariableAccess in a
try
-with-resources statement (14.20.3)
A name is syntactically classified as a MethodName in this context:
- Before the "
(
" in a method invocation expression (15.12)
A name is syntactically classified as a PackageOrTypeName in these contexts:
To the left of the "
.
" in a qualified TypeNameIn a type-import-on-demand declaration (7.5.2)
A name is syntactically classified as an AmbiguousName in these contexts:
To the left of the "
.
" in a qualified ExpressionNameTo the left of the rightmost
.
that occurs before the "(
" in a method invocation expressionTo the left of the "
.
" in a qualified AmbiguousNameIn the default value clause of an annotation
typeelement declaration (9.6.2)To the right of an "
=
" in an an element-value pair (9.7.1)To the left of
::
in a method reference expression (15.13)
The effect of syntactic classification is to restrict certain kinds of entities to certain parts of expressions:
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
typemay appear in an expression only as part of a class literal (15.8.2), a qualifiedthis
expression (15.8.4), a class instance creation expression (15.9), an array creation expression (15.10.1), a cast expression (15.16), aninstanceof
expression (15.20.2), an enum constant (8.9), 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.5.4 Meaning of PackageOrTypeNames
6.5.4.1 Simple PackageOrTypeNames
If the PackageOrTypeName, Q, is a valid TypeIdentifier and occurs in the scope of a type class, interface, or type parameter 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 Id is a valid TypeIdentifier and the type class, interface, type parameter, or package denoted by Q has a member type class or interface 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 exactly one declaration of a type class, interface, or type parameter with this name (6.3), or a compile-time error occurs.
The meaning of the type name is that type class, interface, or type parameter.
6.5.5.2 Qualified Type Names
If a type name is of the form Q.Id, then Q must be either the name of a type in a package uniquely visible to the current module class, interface, or type parameter, or the name of a package uniquely visible to the current module (7.4.3).
If an enclosing class, interface, or type parameter has a resolvable name, it shouldn't matter whether its package is uniquely visible, or even whether it is a member of a package at all (e.g., local classes and type parameters are not package members).
If Id names exactly one accessible type class or interface (6.6) that is a member of the type class, interface, type parameter, or package denoted by Q, then the qualified type name denotes that type class or interface.
If Id does not name a member type class or interface within Q (8.5, 9.5), or the member type class or interface named Id within Q is not accessible (6.6), or Id names more than one member type class or interface within Q, then a compile-time error occurs.
Example 6.5.5.2-1. Qualified Type Names
class Test {
public static void main(String[] args) {
java.util.Date date =
new java.util.Date(System.currentTimeMillis());
System.out.println(date.toLocaleString());
}
}
This program 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 class, interface, or type parameter, or a package, which it is, and then look to see if the type Date
is accessible in this package.
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, classes, interfaces, type parameters, and reference types. When the name of such a member is classified from its context (6.5.1) as a qualified type name (denoting a member of a package, or reference type class, interface, or type parameter, 6.5.5.2) or a qualified expression name (denoting a member of a reference type, 6.5.6.2), access control is applied.
For example, a single-type-import declaration uses a qualified type name (7.5.1), so the named
typeclass or interface must be accessible from the compilation unit containing theimport
declaration. As another example, a class declaration may use a qualified type name for a superclass type (8.1.5), so again the namedtypeclass must be accessible.
Some obvious expressions are "missing" from context classification in 6.5.1: field access on a Primary (15.11.1), method invocation on a Primary (15.12), method reference via a Primary (15.13), and the instantiated class in a qualified class instance creation (15.9). Each of these expressions uses identifiers, rather than names, for the reason given in 6.2. Consequently, access control to members (whether fields, methods,
or typesclasses, or interfaces) is applied explicitly by field access expressions, method invocation expressions, method reference expressions, and qualified class instance creation expressions. (Note that access to a field may also be denoted by a qualified name occuring as a postfix expression.)
In addition, many statements and expressions allow the use of types
rather thanthat are not expressed exclusively with type names. For example, a class declaration may use a parameterized type (4.5) to denote a superclass type. Because a parameterized type is not a qualified type name, it is necessary for the class declaration to explicitly perform access control for the denoted superclass. Consequently, most of the statements and expressions that provide contexts in 6.5.1 to classify a TypeName also perform their own access control checks.
Beyond access to members of a package,
or reference typeclass, interface, or type parameter, there is the matter of access to constructors of areference typeclass. Access control must be checked when a constructor is invoked explicitly or implicitly. Consequently, access control is checked by an explicit constructor invocation statement (8.8.7.1) and by a class instance creation expression (15.9.3). Such checks are necessary because 6.5.1 has no mention of explicit constructor invocation statements (because they reference constructor names indirectly) and is unaware of the distinction between the classtypedenoted by an unqualified class instance creation expression and a constructor of that classtype. Also, constructors do not have qualified names, so we cannot rely on access control being checked during classification of qualified type names.
Accessibility affects inheritance of class members (8.2), including hiding and method overriding (8.4.8.1).
Chapter 7: Packages and Modules
7.3 Compilation Units
CompilationUnit is the goal symbol (2.1) for the syntactic grammar (2.3) of Java programs. It is defined by the following production:
- CompilationUnit:
- OrdinaryCompilationUnit
- ModularCompilationUnit
- OrdinaryCompilationUnit:
- [PackageDeclaration] {ImportDeclaration} {
TypeDeclarationTopLevelClassOrInterfaceDeclaration } - ModularCompilationUnit:
- {ImportDeclaration} ModuleDeclaration
An ordinary compilation unit consists of three parts, each of which is optional:
A
package
declaration (7.4), giving the fully qualified name (6.7) of the package to which the compilation unit belongs.A compilation unit that has no
package
declaration is part of an unnamed package (7.4.2).import
declarations (7.5) that allowtypesclasses and interfaces from other packages andstatic
members oftypesclasses and interfaces to be referred to using their simple names.Top level
typedeclarations(7.6)ofclass and interface typesclasses and interfaces (7.6).
A modular compilation unit consists of a module
declaration (7.7), optionally preceded by import
declarations. The import
declarations allow types classes and interfaces from packages in this module and other modules, as well as static
members of types classes and interfaces, to be referred to using their simple names within the module
declaration.
Every compilation unit implicitly imports every public
type class or interface name declared in the predefined package java.lang
, as if the declaration import java.lang.*;
appeared at the beginning of each compilation unit immediately after any package
declaration. As a result, the names of all those types classes and interfaces are available as simple names in every compilation unit.
The host system determines which compilation units are observable, except for the compilation units in the predefined package java
and its subpackages lang
and io
, which are all always observable.
Each observable compilation unit may be associated with a module, as follows:
The host system may determine that an observable ordinary compilation unit is associated with a module chosen by the host system, except for (i) the ordinary compilation units in the predefined package
java
and its subpackageslang
andio
, which are all associated with thejava.base
module, and (ii) any ordinary compilation unit in an unnamed package, which is associated with a module as specified in 7.4.2.The host system must determine that an observable modular compilation unit is associated with the module declared by the modular compilation unit.
The observability of a compilation unit influences the observability of its package (7.4.3), while the association of an observable compilation unit with a module influences the observability of that module (7.7.6).
When compiling the modular and ordinary compilation units associated with a module M, the host system must respect the dependences specified in M's declaration. Specifically, the host system must limit the ordinary compilation units that would otherwise be observable, to only those that are visible to M. The ordinary compilation units that are visible to M are the observable ordinary compilation units associated with the modules that are read by M. The modules read by M are given by the result of resolution, as described in the java.lang.module
package specification, with M as the only root module. The host system must perform resolution to determine the modules read by M; it is a compile-time error if resolution fails for any of the reasons described in the java.lang.module
package specification.
The readability relation is reflexive, so M reads itself, and thus all of the modular and ordinary compilation units associated with M are visible to M.
The modules read by M drive the packages that are uniquely visible to M (7.4.3), which in turn drives both the top level packages in scope and the meaning of package names for code in the modular and ordinary compilation units associated with M (6.3, 6.5.3, 6.5.5).
The rules above ensure that
package/typenames used in annotations in a modular compilation unit (in particular, annotations applied to the module declaration) are interpreted as if they appeared in an ordinary compilation unit associated with the module.
Types Classes and interfaces declared in different ordinary compilation units can refer to each other, circularly. A Java compiler must arrange to compile all such types classes and interfaces at the same time.
7.5 Import Declarations
An import declaration allows a named type or a class, interface, or static
member to be referred to by a simple name (6.2) that consists of a single identifier.
Without the use of an appropriate import declaration, the only way to refer to a type a reference to a class or interface declared in another package, or a static
member of another type class or interface, is would typically need to use a fully qualified name (6.7).
Problems with the original claim:
A member class could be accessed with a partially qualified name by importing its declaring class.
Members of a superclass are in scope via inheritance, without any need to import them.
- ImportDeclaration:
- SingleTypeImportDeclaration
- TypeImportOnDemandDeclaration
- SingleStaticImportDeclaration
- StaticImportOnDemandDeclaration
A single-type-import declaration (7.5.1) imports a single named
typeclass or interface, by mentioning its canonical name (6.7).A type-import-on-demand declaration (7.5.2) imports all the accessible
typesclasses and interfaces of a namedtype or namedpackage, class, or interface as needed, by mentioning the canonical name of atype orpackage, class, or interface.A single-static-import declaration (7.5.3) imports all accessible
static
members with a given name from atypeclass or interface, by giving its canonical name.A static-import-on-demand declaration (7.5.4) imports all accessible
static
members of a namedtypeclass or interface as needed, by mentioning the canonical name of atypeclass or interface.
The scope and shadowing of a type class, interface, or member imported by these declarations is specified in 6.3 and 6.4.
An
import
declaration makestypesclasses, interfaces, or members available by their simple names only within the compilation unit that actually contains theimport
declaration. The scope of thetype(s)class(es), interface(s), or member(s) introduced by animport
declaration specifically does not include other compilation units in the same package, otherimport
declarations in the current compilation unit, or apackage
declaration in the current compilation unit (except for the annotations of apackage
declaration).
7.5.1 Single-Type-Import Declarations
A single-type-import declaration imports a single type class or interface by giving its canonical name, making it available under a simple name in the module, class, and interface declarations of the compilation unit in which the single-type-import declaration appears.
- SingleTypeImportDeclaration:
import
TypeName;
The TypeName must be the canonical name of a class type, interface type, enum type, or annotation type or interface (6.7).
The type class or interface must be either a member of a named package, or a member of a type class or interface whose outermost lexically enclosing type class or interface declaration (8.1.3) is a member of a named package, or a compile-time error occurs.
It is a compile-time error if the named type class or interface is not accessible (6.6).
If two single-type-import declarations in the same compilation unit attempt to import types classes or interfaces with the same simple name, then a compile-time error occurs, unless the two types classes or interfaces are the same type, in which case the duplicate declaration is ignored.
If the type class or interface imported by the single-type-import declaration is declared in the compilation unit that contains the import
declaration, the import
declaration is ignored.
If a single-type-import declaration imports a type class or interface whose simple name is n, and the compilation unit also declares a top level type class or interface (7.6) whose simple name is n, a compile-time error occurs.
If a compilation unit contains both a single-type-import declaration that imports a type class or interface whose simple name is n, and a single-static-import declaration (7.5.3) that imports a type class or interface whose simple name is n, a compile-time error occurs, unless the two types classes or interfaces are the same type, in which case the duplicate declaration is ignored.
Example 7.5.1-1. Single-Type-Import
import java.util.Vector;
causes the simple name Vector
to be available within the class and interface declarations in a compilation unit. Thus, the simple name Vector
refers to the type class declaration Vector
in the package java.util
in all places where it is not shadowed (6.4.1) or obscured (6.4.2) by a declaration of a field, parameter, local variable, or nested type class or interface declaration with the same name.
Note that the actual declaration of java.util.Vector
is generic (8.1.2). Once imported, the name Vector
can be used without qualification in a parameterized type such as Vector<String>
, or as the raw type Vector
. A related limitation of the import
declaration is that a nested type member class or interface declared inside a generic type class or interface declaration can be imported, but its outer type is always erased.
Example 7.5.1-2. Duplicate Type Class or Interface Declarations
This program:
import java.util.Vector;
class Vector { Object[] vec; }
causes a compile-time error because of the duplicate declaration of Vector
, as does:
import java.util.Vector;
import myVector.Vector;
where myVector
is a package containing the compilation unit:
package myVector;
public class Vector { Object[] vec; }
Example 7.5.1-3. No Import of a Subpackage
Note that an import
declaration cannot import a subpackage, only a type class or interface.
For example, it does not work to try to import java.util
and then use the name util.Random
to refer to the type java.util.Random
:
import java.util;
class Test { util.Random generator; }
// incorrect: compile-time error
Example 7.5.1-4. Importing a Type Name that is also a Package Name
Package names and type names are usually different under the naming conventions described in 6.1. Nevertheless, in a contrived example where there is an unconventionally-named package Vector
, which declares a public class whose name is Mosquito
:
package Vector;
public class Mosquito { int capacity; }
and then the compilation unit:
package strange;
import java.util.Vector;
import Vector.Mosquito;
class Test {
public static void main(String[] args) {
System.out.println(new Vector().getClass());
System.out.println(new Mosquito().getClass());
}
}
the single-type-import declaration importing class Vector
from package java.util
does not prevent the package name Vector
from appearing and being correctly recognized in subsequent import
declarations. The example compiles and produces the output:
class java.util.Vector
class Vector.Mosquito
7.5.2 Type-Import-on-Demand Declarations
A type-import-on-demand declaration allows all accessible types classes and interfaces of a named package, class, or interface or type to be imported as needed.
- TypeImportOnDemandDeclaration:
import
PackageOrTypeName.
*
;
The PackageOrTypeName must be the canonical name (6.7) of a package, a class type, or an interface type, an enum type, or an annotation type.
If the PackageOrTypeName denotes a type class or interface (6.5.4), then the type class or interface must be either a member of a named package, or a member of a type class or interface whose outermost lexically enclosing type class or interface declaration (8.1.3) is a member of a named package, or a compile-time error occurs.
It is a compile-time error if the named package is not uniquely visible to the current module (7.4.3), or if the named type class or interface is not accessible (6.6).
It is not a compile-time error to name either java.lang
or the named package of the current compilation unit in a type-import-on-demand declaration. The type-import-on-demand declaration is ignored in such cases.
Two or more type-import-on-demand declarations in the same compilation unit may name the same type or package, class, or interface. All but one of these declarations are considered redundant; the effect is as if that type was imported only once.
If a compilation unit contains both a type-import-on-demand declaration and a static-import-on-demand declaration (7.5.4) that name the same type class or interface, the effect is as if the static
member types classes and interfaces of that type class or interface (8.5, 9.5) were imported only once.
Example 7.5.2-1. Type-Import-on-Demand
import java.util.*;
causes the simple names of all public
types classes and interfaces declared in the package java.util
to be available within the class and interface declarations of the compilation unit. Thus, the simple name Vector
refers to the type class Vector
in of the package java.util
in all places in the compilation unit where that type class declaration is not shadowed (6.4.1) or obscured (6.4.2).
The declaration might be shadowed by a single-type-import declaration of a type class or interface whose simple name is Vector
; by a type class or interface named Vector
and declared in the package to which the compilation unit belongs; or any nested classes or interfaces.
The declaration might be obscured by a declaration of a field, parameter, or local variable named Vector
.
(It would be unusual for any of these conditions to occur.)
7.5.3 Single-Static-Import Declarations
A single-static-import declaration imports all accessible static
members with a given simple name from a type class or interface. This makes these static
members available under their simple name in the module, class, and interface declarations of the compilation unit in which the single-static-import declaration appears.
- SingleStaticImportDeclaration:
import
static
TypeName.
Identifier;
The TypeName must be the canonical name (6.7) of a class type, interface type, enum type, or annotation type or interface.
The type class or interface must be either a member of a named package, or a member of a type class or interface whose outermost lexically enclosing type class or interface declaration (8.1.3) is a member of a named package, or a compile-time error occurs.
It is a compile-time error if the named type class or interface is not accessible (6.6).
The Identifier must name at least one static
member of the named type class or interface. It is a compile-time error if there is no static
member of that name, or if all of the named members are not accessible.
It is permissible for one single-static-import declaration to import several fields, classes, or interfaces or types with the same name, or several methods with the same name and signature. This occurs when the named type class or interface inherits multiple fields, member types classes, member interfaces, or methods, all with the same name, from its own supertypes.
If two single-static-import declarations in the same compilation unit attempt to import types classes or interfaces with the same simple name, then a compile-time error occurs, unless the two types classes or interfaces are the same type, in which case the duplicate declaration is ignored.
If a single-static-import declaration imports a type class or interface whose simple name is n, and the compilation unit also declares a top level type class or interface (7.6) whose simple name is n, a compile-time error occurs.
If a compilation unit contains both a single-static-import declaration that imports a type class or interface whose simple name is n, and a single-type-import declaration (7.5.1) that imports a type class or interface whose simple name is n, a compile-time error occurs, unless the two types classes or interfaces are the same type, in which case the duplicate declaration is ignored.
7.5.4 Static-Import-on-Demand Declarations
A static-import-on-demand declaration allows all accessible static
members of a named type class or interface to be imported as needed.
- StaticImportOnDemandDeclaration:
import
static
TypeName.
*
;
The TypeName must be the canonical name (6.7) of a class type, interface type, enum type, or annotation type or interface.
The type class or interface must be either a member of a named package, or a member of a type class or interface whose outermost lexically enclosing type class or interface declaration (8.1.3) is a member of a named package, or a compile-time error occurs.
It is a compile-time error if the named type class or interface is not accessible (6.6).
Two or more static-import-on-demand declarations in the same compilation unit may name the same type class or interface; the effect is as if there was exactly one such declaration.
Two or more static-import-on-demand declarations in the same compilation unit may name the same member; the effect is as if the member was imported exactly once.
It is permissible for one static-import-on-demand declaration to import several fields, classes, or interfaces or types with the same name, or several methods with the same name and signature. This occurs when the named type class or interface inherits multiple fields, member types classes, member interfaces, or methods, all with the same name, from its own supertypes.
If a compilation unit contains both a static-import-on-demand declaration and a type-import-on-demand declaration (7.5.2) that name the same type class or interface, the effect is as if the static
member types classes and interfaces of that type class or interface (8.5, 9.5) were imported only once.
7.6 Top Level Type Class and Interface Declarations
A top level type class or interface declaration declares a top level class type (8 8.1) or a top level interface type (9 9.1).
TypeDeclaration:TopLevelClassOrInterfaceDeclaration:- ClassDeclaration
- InterfaceDeclaration
;
Extra "
;
" tokens appearing at the level oftypeclass or interface declarations in a compilation unit have no effect on the meaning of the compilation unit. Stray semicolons are permitted in the Java programming language solely as a concession to C++ programmers who are used to placing ";
" after a class declaration. They should not be used in new Java code.
In the absence of an access modifier, a top level type class or interface has package access: it is accessible only within ordinary compilation units of the package in which it is declared (6.6.1). A type class or interface may be declared public
to grant access to the type class or interface from code in other packages of the same module, and potentially from code in packages of other modules.
It is a compile-time error if a top level type class or interface declaration contains any one of the following access modifiers: protected
, private
, or static
.
It is a compile-time error if the name of a top level type class or interface appears as the name of any other top level class or interface type declared in the same package.
The scope and shadowing of a top level type class or interface is specified in 6.3 and 6.4.
The fully qualified name of a top level type class or interface is specified in 6.7.
Example 7.6-1. Conflicting Top Level Type Class or Interface Declarations
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
Here, 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 compile-time error 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 name of a class to also name a type class or interface 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. Thus, in this program:
package test;
import java.util.*;
class Vector {} // 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).
Example 7.6-2. Scope of Top Level Types Classes and Interfaces
package points;
class Point {
int x, y; // coordinates
PointColor color; // color of this point
Point next; // next point with this color
static int nPoints;
}
class PointColor {
Point first; // first point with this color
PointColor(int color) { this.color = color; }
private int color; // color components
}
This program defines two classes that use each other in the declarations of their class members. Because the class types classes Point
and PointColor
have all the type class declarations in package points
, including all those in the current compilation unit, as their scope, this program compiles correctly. That is, forward reference is not a problem.
Example 7.6-3. Fully Qualified Names
class Point { int x, y; }
In this code, the class Point
is declared in a compilation unit with no package
declaration, and thus Point
is its fully qualified name, whereas in the code:
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 (6.1).)
An implementation of the Java SE Platform must keep track of types classes and interfaces within packages by the combination of their enclosing module names and their binary names (13.1). Multiple ways of naming a type class or interface must be expanded to binary names to make sure that such names are understood as referring to the same type class or interface.
For example, if a compilation unit contains the single-type-import declaration (7.5.1):
import java.util.Vector;
then within that compilation unit, the simple name
Vector
and the fully qualified namejava.util.Vector
refer to the sametypeclass.
If and only if packages are stored in a file system (7.2), the host system may choose to enforce the restriction that it is a compile-time error if a type class or interface is not found in a file under a name composed of the type class or interface name plus an extension (such as .java
or .jav
) if either of the following is true:
The
typeclass or interface is referred to by code in other ordinary compilation units of the package in which thetypeclass or interface is declared.The
typeclass or interface is declaredpublic
(and therefore is potentially accessible from code in other packages).
This restriction implies that there must be at most one such
typeclass or interface per compilation unit. This restriction makes it easy for a Java compiler to find a named class or interface within a package. In practice, many programmers choose to put each class or interfacetypein its own compilation unit, whether or not it ispublic
or is referred to by code in other compilation units.
For example, the source code for a
public
typewet.sprocket.Toad
would be found in a fileToad.java
in the directorywet/sprocket
, and the corresponding object code would be found in the fileToad.class
in the same directory.
7.7 Module Declarations
7.7.3 Service Consumption
The uses
directive specifies a service for which the current module may discover providers via java.util.ServiceLoader
.
The service must be a class type, an interface type, or an annotation type. It is a compile-time error if a uses
directive specifies an enum type class (8.9) as the service.
As a resolvable TypeName, the service will be a class or interface. The only (and somewhat odd) extra constraint here is that it must not be an enum class.
The service may be declared in the current module or in another module. If the service is not declared in the current module, then the service must be accessible to code in the current module (6.6), or a compile-time error occurs.
It is a compile-time error if more than one uses
directive in a module declaration specifies the same service.
7.7.4 Service Provision
The provides
directive specifies a service for which the with
clause specifies one or more service providers to java.util.ServiceLoader
.
The service must be a class type, an interface type, or an annotation type. It is a compile-time error if a provides
directive specifies an enum type class (8.9) as the service.
See comment in 7.7.3.
The service may be declared in the current module or in another module. If the service is not declared in the current module, then the service must be accessible to code in the current module (6.6), or a compile-time error occurs.
Every service provider must be a public
class type or an interface type, that is that is top level or public
, andnested static
, or a compile-time error occurs.
There will eventually be some ambiguity in what "nested static
" means. We can resolve it by just eliminating the word "nested"—any static
class or interface that can be successfully referenced is fine.
Every service provider must be declared in the current module, or a compile-time error occurs.
If a service provider explicitly declares a public
constructor with no formal parameters, or implicitly declares a public
default constructor (8.8.9), then that constructor is called the provider constructor.
If a service provider explicitly declares a public
static
method called provider
with no formal parameters, then that method is called the provider method.
If a service provider has a provider method, then its return type must (i) either be declared in the current module, or be declared in another module and be accessible to code in the current module; and (ii) be a subtype of the service specified in the provides
directive; or a compile-time error occurs.
While a service provider that is specified by a
provides
directive must be declared in the current module, its provider method may have a return type that is declared in another module. Also, note that when a service provider declares a provider method, the service provider itself need not be a subtype of the service.
If a service provider does not have a provider method, then that service provider must have a provider constructor and must be a subtype of the service specified in the provides
directive, or a compile-time error occurs.
It is a compile-time error if more than one provides
directive in a module declaration specifies the same service.
It is a compile-time error if the with
clause of a given provides
directive specifies the same service provider more than once.
Chapter 8: Classes
Class declarations define new reference types classes and describe how they are implemented (8.1).
A top level class (7.6) is a class that is not a nested class declared at the top level of a compilation unit.
A nested class is any class whose declaration occurs within the body of another class or interface. A nested class may be a member class (8.5, 9.5), a local class (14.3), or an anonymous class (15.9.5).
An inner class (8.1.3) is a nested class that can refer to enclosing class instances, local variables, and type variables.
An enum class (8.9) is a class declared with special syntax that defines a small set of named class instances.
This chapter discusses the common semantics of all classes - top level (7.6) and nested (including member classes (8.5, 9.5), local classes (14.3) and anonymous classes (15.9.5)). Details that are specific to particular kinds of classes are discussed in the sections dedicated to these constructs.
A named class may be declared abstract
(8.1.1.1) and must be declared abstract if it is incompletely implemented; such a class cannot be instantiated, but can be extended by subclasses. A class may be declared final
(8.1.1.2), in which case it cannot have subclasses. If a class is declared A class can use access control (6.6) to prevent references to the class from other classes, interfaces, packages, or modules. Each class except public
, then it can be referred to from code in any package of its module and potentially from code in other modules.Object
is an extension of (that is, a subclass of) a single existing class (8.1.4) and may implement interfaces (8.1.5). Classes may be generic (8.1.2), that is, they may declare type variables whose bindings may differ among different instances of the class.
Clarifications to better reflect the full domain of class declarations.
Classes may be decorated with annotations (9.7) just like any other kind of declaration.
The body of a class declares members (fields, and methods, and nested classes, and interfaces), instance and static initializers, and constructors (8.1.6). The scope (6.3) of a member (8.2) is the entire body of the declaration of the class to which the member belongs. Field, method, member class, member interface, and constructor declarations may include the access modifiers (6.6) public
, protected
, or private
. The members of a class include both declared and inherited members (8.2). Newly declared fields can hide fields declared in a superclass or superinterface. Newly declared class members and interface members member classes and interfaces can hide class or interface members member classes and interfaces declared in a superclass or superinterface. Newly declared methods can hide, implement, or override methods declared in a superclass or superinterface.
Field declarations (8.3) describe class variables, which are incarnated once, and instance variables, which are freshly incarnated for each instance of the class. A field may be declared final
(8.3.1.2), in which case it can be assigned to only once. Any field declaration may include an initializer.
Member class declarations (8.5) describe nested classes that are members of the surrounding class. Member classes may be static
, in which case they have no access to the instance variables of the surrounding class; or they may be inner classes (8.1.3).
The earlier introduction of inner classes makes these details redundant.
Member interface declarations (8.5) describe nested interfaces that are members of the surrounding class.
Method declarations (8.4) describe code that may be invoked by method invocation expressions (15.12). A class method is invoked relative to the class type; an instance method is invoked with respect to some particular object that is an instance of a class type. A method whose declaration does not indicate how it is implemented must be declared abstract
. A method may be declared final
(8.4.3.3), in which case it cannot be hidden or overridden. A method may be implemented by platform-dependent native
code (8.4.3.4). A synchronized
method (8.4.3.6) automatically locks an object before executing its body and automatically unlocks the object on return, as if by use of a synchronized
statement (14.19), thus allowing its activities to be synchronized with those of other threads (17).
Method names may be overloaded (8.4.9).
Instance initializers (8.6) are blocks of executable code that may be used to help initialize an instance when it is created (15.9).
Static initializers (8.7) are blocks of executable code that may be used to help initialize a class.
Constructors (8.8) are similar to methods, but cannot be invoked directly by a method call; they are used to initialize new class instances. Like methods, they may be overloaded (8.8.8).
8.1 Class Declarations
A class declaration specifies a new named reference type a new class.
There are two kinds of class declarations: normal class declarations and enum declarations.
- ClassDeclaration:
- NormalClassDeclaration
- EnumDeclaration
- NormalClassDeclaration:
- {ClassModifier}
class
TypeIdentifier [TypeParameters]
[SuperclassClassExtends] [SuperinterfacesClassImplements] ClassBody
The productions could be named SuperclassType and SuperinterfaceTypes, but it seems appropriate to emphasize the keyword they use (compare the Throws production).
A class is also implicitly declared by a ClassInstanceCreationExpression (15.9.5) or EnumConstant (8.9.1) that ends with a class body.
The rules in this section apply to all class declarations, including enum declarations. However, special rules apply to enum declarations with regard to class modifiers, inner classes, and superclasses; these rules are stated in 8.9.
A discussion about how different declaration forms for classes (including enum declarations and anonymous class declarations) relate to the rules specified throughout Chapter 8 already appears in 8. It's confusing to repeat it here.
The TypeIdentifier in a class declaration specifies the name of the class.
It is a compile-time error if a class has the same simple name as any of its enclosing classes or interfaces.
The scope and shadowing of a class declaration is specified in 6.3 and 6.4.
8.1.1 Class Modifiers
A class declaration may include class modifiers.
- ClassModifier:
- (one of)
- Annotation
public
protected
private
abstract
static
final
strictfp
The rules for annotation modifiers on a class declaration are specified in 9.7.4 and 9.7.5.
The access modifier public
(6.6) pertains only to top level classes (7.6) and member classes (8.5, 9.5), not to local classes (14.3) or anonymous classes (15.9.5).
The access modifiers protected
, and private
, and static
pertain only to member classes within a directly enclosing class declaration (8.5).
The modifier static
pertains only to member classes (8.5.1), not to top level or local or anonymous classes.
This is not the place for comprehensive lists and rules. The purpose of these sentences is to provide some cross references for readers who'd like to know how certain modifiers are used. More details can be found there.
It is a compile-time error if the same keyword appears more than once as a modifier for a class declaration, or if a class declaration has more than one of the access modifiers public
, protected
, and private
(6.6).
If two or more (distinct) class modifiers appear in a class declaration, then it is customary, though not required, that they appear in the order consistent with that shown above in the production for ClassModifier.
8.1.1.3 strictfp
Classes
The effect of the strictfp
modifier is to make all float
or double
expressions within the class declaration (including within variable initializers, instance initializers, static initializers, and constructors) be explicitly FP-strict (15.4).
This implies that all methods declared in the class, and all nested types classes and interfaces declared in the class, are implicitly strictfp
.
8.1.3 Inner Classes and Enclosing Instances
An inner class is a nested class that is not explicitly or implicitly declared static
.
An inner class may be a non-static
member class (8.5), a local class (14.3), or an anonymous class (15.9.5). A member class of an interface is implicitly static
(9.5) so is never considered to be an inner class.
It is a compile-time error if an inner class declares a static initializer (8.7).
It is a compile-time error if an inner class declares a member that is explicitly or implicitly static
, unless the member is a constant variable (4.12.4).
An inner class may inherit static
members that are not constant variables even though it cannot declare them.
A nested class that is not an inner class may declare static
members freely, in accordance with the usual rules of the Java programming language.
Example 8.1.3-1. Inner Class Declarations and Static Members
class HasStatic {
static int j = 100;
}
class Outer {
class Inner extends HasStatic {
static final int x = 3; // OK: constant variable
static int y = 4; // Compile-time error: an inner class
}
static class NestedButNotInner{
static int z = 5; // OK: not an inner class
}
interface NeverInner {} // Interfaces are never inner
}
A statement or expression occurs in a static context if and only if the innermost method, constructor, instance initializer, static initializer, field initializer, or explicit constructor invocation statement enclosing the statement or expression is a static method, a static initializer, the variable initializer of a static variable, or an explicit constructor invocation statement (8.8.7.1).
An inner class C is a direct inner class of a class or interface O if O is the immediately enclosing type class or interface declaration of C and the declaration of C does not occur in a static context.
If an inner class is a local class or an anonymous class, it may be declared in a static context, and in that case is not considered an inner class of any enclosing class or interface.
A class C is an inner class of class or interface O if it is either a direct inner class of O or an inner class of an inner class of O.
It is unusual, but possible, for the immediately enclosing
typeclass or interface declaration of an inner class to be an interface. This only occurs if the class is a local or anonymous class declared in a default or static method body (9.4).Specifically, it occurs if an anonymous or local class is declared in a default method body, or a member class is declared in the body of an anonymous class that is declared in a default method body.
In that second example, the immediately enclosing class or interface declaration is the anonymous class, not the interface.
A class or interface O is the zeroth lexically enclosing type declaration of itself.
A class O is the n'th lexically enclosing type declaration of a class C if it is the immediately enclosing type declaration of the n-1'th lexically enclosing type declaration of C.
An instance i of a direct inner class C of a class or interface O is associated with an instance of O, known as the immediately enclosing instance of i. The immediately enclosing instance of an object, if any, is determined when the object is created (15.9.2).
An object o is the zeroth lexically enclosing instance of itself.
An object o is the n'th lexically enclosing instance of an instance i if it is the immediately enclosing instance of the n-1'th lexically enclosing instance of i.
An instance of an inner class I a local class or an anonymous class whose declaration occurs in a static context has no lexically enclosing instances. However, if I is immediately declared within a static method or static initializer then I does have an enclosing block, which is the innermost block statement lexically enclosing the declaration of I.
The term "enclosing block" is never used outside of this paragraph. This section already includes an overwhelming amount of new terminology, so we're better off without this additional definition.
For every superclass S of C which is itself a direct inner class of a class or interface SO, there is an instance of SO associated with i, known as the immediately enclosing instance of i with respect to S. The immediately enclosing instance of an object with respect to its class's direct superclass, if any, is determined when the superclass constructor is invoked via an explicit constructor invocation statement (8.8.7.1).
When an inner class (whose declaration does not occur in a static context) refers to an instance variable that is a member of a lexically enclosing type class or interface declaration, the variable of the corresponding lexically enclosing instance is used.
Any local variable, formal parameter, or exception parameter used but not declared in an inner class must either be declared final
or be effectively final (4.12.4), or a compile-time error occurs where the use is attempted.
Any local variable used but not declared in an inner class must be definitely assigned (16) before the body of the inner class, or a compile-time error occurs.
Similar rules on variable use apply in the body of a lambda expression (15.27.2).
A blank final
field (4.12.4) of a lexically enclosing type class or interface declaration may not be assigned within an inner class, or a compile-time error occurs.
Example 8.1.3-2. Inner Class Declarations
class Outer {
int i = 100;
static void classMethod() {
final int l = 200;
class LocalInStaticContext {
int k = i; // Compile-time error
int m = l; // OK
}
}
void foo() {
class Local { // A local class
int j = i;
}
}
}
The declaration of class LocalInStaticContext
occurs in a static context due to being within the static method classMethod
. Instance variables of class Outer
are not available within the body of a static method. In particular, instance variables of Outer
are not available inside the body of LocalInStaticContext
. However, local variables from the surrounding method may be referred to without error (provided they are declared final
or are effectively final).
Inner classes whose declarations do not occur in a static context may freely refer to the instance variables of their enclosing type class declaration. An instance variable is always defined with respect to an instance. In the case of instance variables of an enclosing type class declaration, the instance variable must be defined with respect to an enclosing instance of that declared type the inner class. For example, the class Local
above has an enclosing instance of class Outer
. As a further example:
class WithDeepNesting {
boolean toBe;
WithDeepNesting(boolean b) { toBe = b; }
class Nested {
boolean theQuestion;
class DeeplyNested {
DeeplyNested(){
theQuestion = toBe || !toBe;
}
}
}
}
Here, every instance of WithDeepNesting.Nested.DeeplyNested
has an enclosing instance of class WithDeepNesting.Nested
(its immediately enclosing instance) and an enclosing instance of class WithDeepNesting
(its 2nd lexically enclosing instance).
8.1.4 Superclasses and Subclasses
The core feature being described here is a class's superclass. "Subclass" is merely a convenient bit of terminology, not significant enough to belong in the title.
The optional extends
clause in a normal class declaration specifies the direct superclass type of the current class.
Superclass:ClassExtends:extends
ClassType
The extends
clause must not appear in the definition of the class Object
, or a compile-time error occurs, because it is the primordial class and has no direct superclass type.
The ClassType must name an accessible class type (6.6), or a compile-time error occurs.
It is a compile-time error if the ClassType names a class that is final
, because final
classes are not allowed to have subclasses (8.1.1.2).
It is a compile-time error if the ClassType names the class Enum
or any invocation of , which can only be extended by an enum class (8.9).Enum
If the ClassType has type arguments, it must denote a well-formed parameterized type (4.5), and none of the type arguments may be wildcard type arguments, or a compile-time error occurs.
Given a (possibly generic) class declaration C<
F1,...,Fn>
(n ≥ 0, C ≠ Object
), the direct superclass of the class type C<
F1,...,Fn>
is the type given in the extends
clause of the declaration of C if an extends
clause is present, or Object
otherwise.
Given a generic class declaration C<
F1,...,Fn>
(n > 0), the direct superclass of the parameterized class type C<
T1,...,Tn>
, where Ti (1 ≤ i ≤ n) is a type, is D<
U1 θ,...,Uk θ>
, where D<
U1,...,Uk>
is the direct superclass of C<
F1,...,Fn>
and θ is the substitution [F1:=T1,...,Fn:=Tn]
.
Covered by 4.10.2. This section is only concerned with the superclass type of a class, not the superclass types of types.
The direct superclass type of a class whose declaration lacks an extends
clause is as follows:
The class
Object
has no direct superclass type.For a class other than
Object
with a normal class declaration, the direct superclass type isObject
.For an enum class E, the direct superclass type is
Enum<
E>
.For an anonymous class, the direct superclass type is defined in 15.9.5.
This section, as indicated in 8, is about all classes, so it's important to define the relation for all classes.
The direct superclass of a class is the class named by its direct superclass type. A class is said to be a direct subclass of its direct superclass. The direct superclass is the class from whose implementation the implementation of the current class is derived.
The subclass superclass relationship is the transitive closure of the direct subclass superclass relationship. A class A is a subclass superclass of class C if either of the following is true:
A is the direct
subclasssuperclass of CThere exists a class B such that A is a subclass of B, and B is a subclass of CWhere a class B is the direct superclass of C, A is a superclass of B, applying this definition recursively.
Class C is said to be a superclass of class A whenever A is a subclass of C.
A class is said to be a direct subclass of its direct superclass, and a subclass of each of its superclasses.
If direct superclass is the fundamental relation being defined here, it's more natural presentationally to get to superclass via transitive closure on that relation, rather than taking a detour through the inverse, subclass.
Example 8.1.4-1. Direct Superclasses and Subclasses
class Point { int x, y; }
final class ColoredPoint extends Point { int color; }
class Colored3DPoint extends ColoredPoint { int z; } // error
Here, the relationships are as follows:
The class
Point
is a direct subclass ofObject
.The class
Object
is the direct superclass of the classPoint
.The class
ColoredPoint
is a direct subclass of classPoint
.The class
Point
is the direct superclass of classColoredPoint
.
The declaration of class Colored3dPoint
causes a compile-time error because it attempts to extend the final class ColoredPoint
.
Example 8.1.4-2. Superclasses and Subclasses
class Point { int x, y; }
class ColoredPoint extends Point { int color; }
final class Colored3dPoint extends ColoredPoint { int z; }
Here, the relationships are as follows:
The class
Point
is a superclass of classColoredPoint
.The class
Point
is a superclass of classColored3dPoint
.The class
ColoredPoint
is a subclass of classPoint
.The class
ColoredPoint
is a superclass of classColored3dPoint
.The class
Colored3dPoint
is a subclass of classColoredPoint
.The class
Colored3dPoint
is a subclass of classPoint
.
A class C directly depends on a type T class or interface A if T A is mentioned in the extends
or implements
clause of C either as a superclass or superinterface, or as a qualifier in the fully qualified form of a superclass or superinterface name.
A class C depends on a reference type T class or interface A if any of the following is true:
C directly depends on
TA.C directly depends on an interface I that depends (9.1.3) on
TA.C directly depends on a class D that depends on
TA (using this definition recursively).
It is a compile-time error if a class depends on itself.
If circularly declared classes are detected at run time, as classes are loaded, then a ClassCircularityError
is thrown (12.2.1).
Example 8.1.4-3. Class Depends on Itself
class Point extends ColoredPoint { int x, y; }
class ColoredPoint extends Point { int color; }
This program causes a compile-time error because class Point
depends on itself.
8.1.5 Superinterfaces
The optional implements
clause in a class declaration lists the names of interfaces interface types that are the direct superinterfaces superinterface types of the class being declared.
Superinterfaces:ClassImplements:implements
InterfaceTypeList- InterfaceTypeList:
- InterfaceType {
,
InterfaceType}
Each InterfaceType must name an accessible interface type (6.6), or a compile-time error occurs.
If an InterfaceType has type arguments, it must denote a well-formed parameterized type (4.5), and none of the type arguments may be wildcard type arguments, or a compile-time error occurs.
It is a compile-time error if the same interface is mentioned as named by a direct superinterface type more than once in a single implements
clause. This is true even if the interface is named in different ways.
Example 8.1.5-1. Illegal Superinterfaces
class Redundant implements java.lang.Cloneable, Cloneable {
int x;
}
This program results in a compile-time error because the names java.lang.Cloneable
and Cloneable
refer to the same interface.
Given a (possibly generic) class declaration C<
F1,...,Fn>
(n ≥ 0, C ≠ Object
), the direct superinterfaces of the class type C<
F1,...,Fn>
are the types given in the implements
clause of the declaration of C, if an implements
clause is present.
Given a generic class declaration C<
F1,...,Fn>
(n > 0), the direct superinterfaces of the parameterized class type C<
T1,...,Tn>
, where Ti (1 ≤ i ≤ n) is a type, are all types I<
U1 θ,...,Uk θ>
, where I<
U1,...,Uk>
is a direct superinterface of C<
F1,...,Fn>
and θ is the substitution [F1:=T1,...,Fn:=Tn]
.
Covered by 4.10.2. This section is only concerned with the superinterface types of a class, not the superinterface types of types.
A class whose declaration lacks an implements
clause has no direct superinterface types, with one exception: an anonymous class may have a superinterface type, as defined in 15.9.5.
An interface is a direct superinterface of a class if the interface is named by one of the direct superinterface types of the class.
An interface type I is a superinterface of class type C if any of the following is true:
I is a direct superinterface of C.
C has some direct superinterface J for which I is a superinterface, using the definition of "superinterface of an interface" given in 9.1.3.
I is a superinterface of the direct superclass of C.
A class can have a superinterface in more than one way.
A class is said to directly implement its direct superinterfaces, and to implement all of its superinterfaces. We also say that a class is a direct subclass of its direct superinterfaces, and a subclass of all of its superinterfaces.
Subclass is traditionally a class-class relationship, but it's often useful to have a noun that describes a class-interface relationship. "Implementing class" can be awkward (e.g., where A is a class or interface, "C is a subclass of A" vs. "C is a subclass or implementing class of A").
A class may not at the same time be a subtype of two interface types declare a direct superclass type and a direct superinterface type, or two direct superinterface types, which are, or which have supertypes (4.10.2) which are, different parameterizations of the same generic interface (9.1.2), or a subtype of a parameterization of a generic interface and a raw type naming that same generic interface. In the case of such a conflict, or a compile-time error occurs.
This requirement was introduced in order to support translation by type erasure (4.6).
Example 8.1.5-2. Superinterfaces
interface Colorable {
void setColor(int color);
int getColor();
}
enum Finish { MATTE, GLOSSY }
interface Paintable extends Colorable {
void setFinish(Finish finish);
Finish getFinish();
}
class Point { int x, y; }
class ColoredPoint extends Point implements Colorable {
int color;
public void setColor(int color) { this.color = color; }
public int getColor() { return color; }
}
class PaintedPoint extends ColoredPoint implements Paintable {
Finish finish;
public void setFinish(Finish finish) {
this.finish = finish;
}
public Finish getFinish() { return finish; }
}
Here, the relationships are as follows:
The interface
Paintable
is a superinterface of classPaintedPoint
.The interface
Colorable
is a superinterface of classColoredPoint
and of classPaintedPoint
.The interface
Paintable
is a subinterface of the interfaceColorable
, andColorable
is a superinterface ofPaintable
, as defined in 9.1.3.
The class PaintedPoint
has Colorable
as a superinterface both because it is a superinterface of ColoredPoint
and because it is a superinterface of Paintable
.
Example 8.1.5-3. Illegal Multiple Inheritance of an Interface
interface I<T> {}
class B implements I<Integer> {}
class C extends B implements I<String> {}
Class C
causes a compile-time error because it attempts to be a subtype of both I<Integer
> and I<String
>.
...
8.1.6 Class Body and Member Declarations
A class body may contain declarations of members of the class, that is, fields (8.3), methods (8.4), classes (8.5), and interfaces (8.5).
A class body may also contain instance initializers (8.6), static initializers (8.7), and declarations of constructors (8.8) for the class.
- ClassBody:
{
{ClassBodyDeclaration}}
- ClassBodyDeclaration:
- ClassMemberDeclaration
- InstanceInitializer
- StaticInitializer
- ConstructorDeclaration
- ClassMemberDeclaration:
- FieldDeclaration
- MethodDeclaration
- ClassDeclaration
- InterfaceDeclaration
;
The scope and shadowing of a declaration of a member m declared in or inherited by a class type C is specified in 6.3 and 6.4.
If C
itselfis a nested class, there may be definitions of the same kind (variable, method, or type) and name as m in enclosing scopes. (The scopes may be blocks, classes, or packages.) In all such cases, the member m declared in or inherited by C shadows (6.4.1) the other definitions of the same kind and name.
8.2 Class Members
The members of a class type are all of the following:
Members inherited from its direct superclass type (8.1.4), except in class
Object
, which has no direct superclass typeMembers inherited from any direct
superinterfacessuperinterface types (8.1.5)Members declared in the body of the class (8.1.6)
Members of a class that are declared private
are not inherited by subclasses of that class.
Only members of a class that are declared protected
or public
are inherited by subclasses declared in a package other than the one in which the class is declared.
Constructors, static initializers, and instance initializers are not members and therefore are not inherited.
We use the phrase the type of a member to denote:
For a field, its type.
For a method, an ordered 4-tuple consisting of:
type parameters: the declarations of any type parameters of the method member.
argument types: a list of the types of the arguments to the method member.
return type: the return type of the method member.
throws
clause: exception types declared in thethrows
clause of the method member.
Fields, methods, and member types classes and interfaces of a class type may have the same name, since they are used in different contexts and are disambiguated by different lookup procedures (6.5). However, this is discouraged as a matter of style.
...
8.3 Field Declarations
The variables of a class type are introduced by field declarations.
...
8.4 Method Declarations
8.4.8 Inheritance, Overriding, and Hiding
A class C inherits from its direct superclass type all concrete methods m (both static
and instance) of the superclass type for which all of the following are true:
m is a member of the direct superclass type of C, D.
m is
public
,protected
, or declared with package access in the same package as C.No method declared in C has a signature that is a subsignature (8.4.2) of the signature of m as a member of D.
It's important that the subsignature test be performed with respect to a method's signature as a member of a particular type. A method's signature can vary depending on type parameter instantiations.
A class C inherits from its direct superclass type and direct superinterfaces superinterface types all abstract
and default (9.4) methods m for which all of the following are true:
m is a member of the direct superclass type or a direct superinterface type, D, of C.
m is
public
,protected
, or declared with package access in the same package as C.No method declared in C has a signature that is a subsignature (8.4.2) of the signature of m as a member of D.
No concrete method inherited by C from its direct superclass type has a signature that is a subsignature of the signature of m as a member of D.
There exists no method m' that is a member of the direct superclass type or a direct superinterface type, D', of C (m distinct from m', D distinct from D'), such that m' overrides from the class or interface of D' (8.4.8.1, 9.4.1.1) the declaration of the method m.
A class does not inherit private
or static
methods from its superinterfaces superinterface types.
Note that methods are overridden or hidden on a signature-by-signature basis. If, for example, a class declares two
public
methods with the same name (8.4.9), and a subclass overrides one of them, the subclass still inherits the other method.
Example 8.4.8-1. Inheritance
interface I1 {
int foo();
}
interface I2 {
int foo();
}
abstract class Test implements I1, I2 {}
Here, the abstract
class Test
inherits the abstract
method foo
from interface I1
and also the abstract
method foo
from interface I2
. The key question in determining the inheritance of foo
from I1
is: does the method foo
in I2
override "from I2
" (9.4.1.1) the method foo
in I1
? No, because I1
and I2
are not subinterfaces of each other. Thus, from the viewpoint of class Test
, the inheritance of foo
from I1
is unfettered; similarly for the inheritance of foo
from I2
. Per 8.4.8.4, class Test
can inherit both foo
methods; obviously it must be declared abstract
, or else override both abstract
foo
methods with a concrete method.
Note that it is possible for an inherited concrete method to prevent the inheritance of an
abstract
or default method. (The concrete method will override theabstract
or default method "from C", per 8.4.8.1 and 9.4.1.1.) Also, it is possible for one supertype method to prevent the inheritance of another supertype method if the former "already" overrides the latter - this is the same as the rule for interfaces (9.4.1), and prevents conflicts in which multiple default methods are inherited and one implementation is clearly meant to supersede the other.
8.4.8.1 Overriding (by Instance Methods)
An instance method mC declared in or inherited by class C, overrides from C another method mA declared in class A, iff all of the following are true:
C is a subclass of A.
C does not inherit mA.
The signature of mC is a subsignature (8.4.2) of the signature of mA as a member of the supertype of C that names A.
In the case of a generic class A, we need to know what type parameters to apply to A before comparing signatures.
One of the following is true:
mA is
public
.mA is
protected
.mA is declared with package access in the same package as C, and either C declares mC or mA is a member of the direct superclass type of C.
mA is declared with package access and mC overrides mA from some superclass of C.
mA is declared with package access and mC overrides a method m' from C (m' distinct from mC and mA), such that m' overrides mA from some superclass of C.
If mC is non-abstract
and overrides from C an abstract
method mA, then mC is said to implement mA from C.
It is a compile-time error if the overridden method, mA, is a static
method.
In this respect, overriding of methods differs from hiding of fields (8.3), for it is permissible for an instance variable to hide a
static
variable.
An instance method mC declared in or inherited by class C, overrides from C another method mI declared in interface I, iff all of the following are true:
I is a superinterface of C.
mI is not
static
.C does not inherit mI.
The signature of mC is a subsignature (8.4.2) of the signature of mI as a member of the supertype of C that names I.
mI is
public
.
The signature of an overriding method may differ from the overridden one if a formal parameter in one of the methods has a raw type, while the corresponding parameter in the other has a parameterized type. This accommodates migration of pre-existing code to take advantage of generics.
The notion of overriding includes methods that override another from some subclass of their declaring class. This can happen in two ways:
A concrete method in a generic superclass can, under certain parameterizations, have the same signature as an abstract method in that class. In this case, the concrete method is inherited and the
abstract
method is not (as described above). The inherited method should then be considered to override its abstract peer from C. (This scenario is complicated by package access: if C is in a different package, then mA would not have been inherited anyway, and should not be considered overridden.)A method inherited from a class can override a superinterface method. (Happily, package access is not a concern here.)
An overridden method can be accessed by using a method invocation expression (15.12) that contains the keyword super
. A qualified name or a cast to a superclass type is not effective in attempting to access an overridden method.
In this respect, overriding of methods differs from hiding of fields.
The presence or absence of the strictfp
modifier has absolutely no effect on the rules for overriding methods and implementing abstract methods. For example, it is permitted for a method that is not FP-strict to override an FP-strict method and it is permitted for an FP-strict method to override a method that is not FP-strict.
...
8.4.8.2 Hiding (by Class Methods)
If a class C declares or inherits a static
method m, then m is said to hide any method m' declared in class or interface A for which all of the following are true:
A is a superclass or superinterface of C.
m' is either aIf A is an interface, m' is an instance method.static
or instance method declared in a superclass of C, or an instance method declared in a superinterface of C.m' is accessible to C (6.6).
The signature of m is a subsignature (8.4.2) of the signature of m'
(8.4.2)as a member of the supertype of C that names A.
The clarification about the type to use when determining the signature is irrelevant to static
methods, which cannot make use of type parameters, but affects how static
methods are matched up with instance methods in supertypes.
It is a compile-time error if a static
method hides an instance method.
In this respect, hiding of methods differs from hiding of fields (8.3), for it is permissible for a
static
variable to hide an instance variable. Hiding is also distinct from shadowing (6.4.1) and obscuring (6.4.2).
A hidden method can be accessed by using a qualified name or by using a method invocation expression (15.12) that contains the keyword super
or a cast to a superclass type.
In this respect, hiding of methods is similar to hiding of fields.
Example 8.4.8.2-1. Invocation of Hidden Class Methods
A class (static
) method that is hidden can be invoked by using a reference whose type is the type of the class that actually contains the declaration of the method. In this respect, hiding of static
methods is different from overriding of instance methods. The example:
class Super {
static String greeting() { return "Goodnight"; }
String name() { return "Richard"; }
}
class Sub extends Super {
static String greeting() { return "Hello"; }
String name() { return "Dick"; }
}
class Test {
public static void main(String[] args) {
Super s = new Sub();
System.out.println(s.greeting() + ", " + s.name());
}
}
produces the output:
Goodnight, Dick
because the invocation of greeting
uses the type of s
, namely Super
, to figure out, at compile time, which class method to invoke, whereas the invocation of name
uses the class of s
, namely Sub
, to figure out, at run time, which instance method to invoke.
8.4.8.3 Requirements in Overriding and Hiding
If a method declaration d1 with return type R1 overrides or hides the declaration of another method d2 with return type R2, then d1 must be return-type-substitutable (8.4.5) for d2, or a compile-time error occurs.
This rule allows for covariant return types - refining the return type of a method when overriding it.
If R1 is not a subtype of R2, then a compile-time unchecked warning occurs, unless suppressed by @SuppressWarnings
(9.6.4.5).
A method that overrides or hides another method, including methods that implement abstract
methods defined in interfaces, may not be declared to throw more checked exceptions than the overridden or hidden method.
In this respect, overriding of methods differs from hiding of fields (8.3), for it is permissible for a field to hide a field of another type.
More precisely, suppose that B is a class or interface, and A is a superclass or superinterface of B, and a method declaration m2 in B overrides or hides a method declaration m1 in A. Then:
If m2 has a
throws
clause that mentions any checked exception types, then m1 must have athrows
clause, or a compile-time error occurs.For every checked exception type listed in the
throws
clause of m2, that same exception class or one of its supertypes must occur in the erasure (4.6) of thethrows
clause of m1; otherwise, a compile-time error occurs.If the unerased
throws
clause of m1 does not contain a supertype of each exception type in thethrows
clause of m2 (adapted, if necessary, to the type parameters of m1), then a compile-time unchecked warning occurs, unless suppressed by@SuppressWarnings
(9.6.4.5).
It is a compile-time error if a type declaration T class or interface C has a member method m1 and there exists a method m2 declared in T C or a supertype superclass or superinterface of T C, A such that all of the following are true:
m1 and m2 have the same name.
m2 is accessible (6.6) from
TC.The signature of m1 is not a subsignature (8.4.2) of the signature of m2 as a member of the supertype of C that names A.
The declared signature of m1 or some method m1 overrides (directly or indirectly) has the same erasure as the declared signature of m2 or some method m2 overrides (directly or indirectly).
These restrictions are necessary because generics are implemented via erasure. The rule above implies that methods declared in the same class with the same name must have different erasures. It also implies that a
type declarationclass or interface cannot implement or extend two distinctinvocationsparameterizations of the same generic interface.
The access modifier of an overriding or hiding method must provide at least as much access as the overridden or hidden method, as follows:
If the overridden or hidden method is
public
, then the overriding or hiding method must bepublic
; otherwise, a compile-time error occurs.If the overridden or hidden method is
protected
, then the overriding or hiding method must beprotected
orpublic
; otherwise, a compile-time error occurs.If the overridden or hidden method has package access, then the overriding or hiding method must not be
private
; otherwise, a compile-time error occurs.
Note that a
private
method cannot be overridden or hidden in the technical sense of those terms. This means that a subclass can declare a method with the same signature as aprivate
method in one of its superclasses, and there is no requirement that the return type orthrows
clause of such a method bear any relationship to those of theprivate
method in the superclass.
...
8.5 Member Type Class and Interface Declarations
A member class is a class whose declaration is directly enclosed in the body of another class or interface declaration (8.1.6, 9.1.4). A member class may be an enum class (8.9).
A member interface is an interface whose declaration is directly enclosed in the body of another class or interface declaration (8.1.6, 9.1.4). A member interface may be an annotation interface (9.6).
The accessibility of a member type class or interface declaration in a class is specified by its access modifier, or by 6.6 if lacking an access modifier.
It is a compile-time error if the same keyword appears more than once as a modifier for a member type declaration in a class, or if a member type declaration has more than one of the access modifiers public
, protected
, and private
(6.6.)
The scope and shadowing of a member type class or interface is specified in 6.3 and 6.4.
If a class declares a member type class or interface with a certain name, then the declaration of that type class or interface is said to hide any and all accessible declarations of member types classes and interfaces with the same name in superclasses and superinterfaces of the class.
In this respect, hiding of member
typesclasses and interfaces is similar to hiding of fields (8.3).
A class inherits from its direct superclass and direct superinterfaces all the non-private
member types classes and interfaces of the superclass and superinterfaces that are both accessible to code in the class and not hidden by a declaration in the class.
It is possible for a class to inherit more than one member type class or interface with the same name, either from its superclass and superinterfaces or from its superinterfaces alone. Such a situation does not in itself cause a compile-time error. However, any attempt within the body of the class to refer to any such member type class or interface by its simple name will result in a compile-time error, because the reference is ambiguous.
There might be several paths by which the same member type class or interface declaration is inherited from an interface. In such a situation, the member type class or interface is considered to be inherited only once, and it may be referred to by its simple name without ambiguity.
8.5.1 Static Member Type Class and Interface Declarations
The static
keyword may modify the declaration of a member type class C within the body of a non-inner class or interface T. Its effect is to declare that C is not an inner class. Just as a static
method of T has no current instance of T in its body, C also has no current instance of T, nor does it have any lexically enclosing instances.
It is a compile-time error if a static
class contains a usage of a non-static
member of an enclosing class.
A member interface is implicitly static
(9.1.1). It is permitted for the declaration of a member interface to redundantly specify the static
modifier.
8.8 Constructor Declarations
8.8.7 Constructor Body
8.8.7.1 Explicit Constructor Invocations
- ExplicitConstructorInvocation:
- [TypeArguments]
this
(
[ArgumentList])
;
- [TypeArguments]
super
(
[ArgumentList])
;
- ExpressionName
.
[TypeArguments]super
(
[ArgumentList])
;
- Primary
.
[TypeArguments]super
(
[ArgumentList])
;
The following productions from 4.5.1 and 15.12 are shown here for convenience:
- TypeArguments:
<
TypeArgumentList>
- ArgumentList:
- Expression {
,
Expression}
Explicit constructor invocation statements are divided into two kinds:
Alternate constructor invocations begin with the keyword
this
(possibly prefaced with explicit type arguments). They are used to invoke an alternate constructor of the same class.Superclass constructor invocations begin with either the keyword
super
(possibly prefaced with explicit type arguments) or a Primary expression or an ExpressionName. They are used to invoke a constructor of the direct superclass. They are further divided:Unqualified superclass constructor invocations begin with the keyword
super
(possibly prefaced with explicit type arguments).Qualified superclass constructor invocations begin with a Primary expression or an ExpressionName. They allow a subclass constructor to explicitly specify the newly created object's immediately enclosing instance with respect to the direct superclass (8.1.3). This may be necessary when the superclass is an inner class.
An explicit constructor invocation statement in a constructor body may not refer to any instance variables or instance methods or inner classes declared in this class or any superclass, or use this
or super
in any expression; otherwise, a compile-time error occurs.
This prohibition on using the current instance explains why an explicit constructor invocation statement is deemed to occur in a static context (8.1.3).
If TypeArguments is present to the left of this
or super
, then it is a compile-time error if any of the type arguments are wildcards (4.5.1).
Let C be the class being instantiated, and let S be the direct superclass of C.
If a superclass constructor invocation statement is unqualified, then:
- If S is an inner member class, but S is not a member of a class enclosing C, then a compile-time error occurs.
If a superclass constructor invocation statement is qualified, then:
If S is not an inner class, or if the declaration of S occurs in a static context, then a compile-time error occurs.
Otherwise, let p be the Primary expression or the ExpressionName immediately preceding "
.super
", and let O be the immediately enclosing class of S. It is a compile-time error if the type of p is not O or a subclass of O, or if the type of p is not accessible (6.6).
The exception types that an explicit constructor invocation statement can throw are specified in 11.2.2.
Evaluation of an alternate constructor invocation statement proceeds by first evaluating the arguments to the constructor, left-to-right, as in an ordinary method invocation; and then invoking the constructor.
Evaluation of a superclass constructor invocation statement proceeds as follows:
Let i be the instance being created. The immediately enclosing instance of i with respect to S (if any) must be determined:
If S is not an inner class, or if the declaration of S occurs in a static context, then no immediately enclosing instance of i with respect to S exists.
If the superclass constructor invocation is unqualified, then S is necessarily a local class or an inner member class.
If S is a local class, then let O be the immediately enclosing
typeclass or interface declaration of S.If S is an inner member class, then let O be the innermost enclosing class of C of which S is a member.
Let n be an integer (n ≥ 1) such that O is the n'th lexically enclosing
typeclass or interface declaration of C.The immediately enclosing instance of i with respect to S is the n'th lexically enclosing instance of
this
.While it may be the case that S is a member of C due to inheritance, the zeroth lexically enclosing instance of
this
(that is,this
itself) is never used as the immediately enclosing instance of i with respect to S.If the superclass constructor invocation is qualified, then the Primary expression or the ExpressionName immediately preceding "
.super
", p, is evaluated.If p evaluates to
null
, aNullPointerException
is raised, and the superclass constructor invocation completes abruptly.Otherwise, the result of this evaluation is the immediately enclosing instance of i with respect to S.
After determining the immediately enclosing instance of i with respect to S (if any), evaluation of the superclass constructor invocation statement proceeds by evaluating the arguments to the constructor, left-to-right, as in an ordinary method invocation; and then invoking the constructor.
Finally, if the superclass constructor invocation statement completes normally, then all instance variable initializers of C and all instance initializers of C are executed. If an instance initializer or instance variable initializer I textually precedes another instance initializer or instance variable initializer J, then I is executed before J.
Execution of instance variable initializers and instance initializers is performed regardless of whether the superclass constructor invocation actually appears as an explicit constructor invocation statement or is provided implicitly. (An alternate constructor invocation does not perform this additional implicit execution.)
Example 8.8.7.1-1. Restrictions on Explicit Constructor Invocation Statements
If the first constructor of ColoredPoint
in the example from 8.8.7 were changed as follows:
class Point {
int x, y;
Point(int x, int y) { this.x = x; this.y = y; }
}
class ColoredPoint extends Point {
static final int WHITE = 0, BLACK = 1;
int color;
ColoredPoint(int x, int y) {
this(x, y, color); // Changed to color from WHITE
}
ColoredPoint(int x, int y, int color) {
super(x, y);
this.color = color;
}
}
then a compile-time error would occur, because the instance variable color
cannot be used by a explicit constructor invocation statement.
Example 8.8.7.1-2. Qualified Superclass Constructor Invocation
In the code below, ChildOfInner
has no lexically enclosing type class or interface declaration, so an instance of ChildOfInner
has no enclosing instance. However, the superclass of ChildOfInner
(Inner
) has a lexically enclosing type class declaration (Outer
), and an instance of Inner
must have an enclosing instance of Outer
. The enclosing instance of Outer
is set when an instance of Inner
is created. Therefore, when we create an instance of ChildOfInner
, which is implicitly an instance of Inner
, we must provide the enclosing instance of Outer
via a qualified superclass invocation statement in ChildOfInner
's constructor. The instance of Outer
is called the immediately enclosing instance of ChildOfInner
with respect to Inner
.
class Outer {
class Inner {}
}
class ChildOfInner extends Outer.Inner {
ChildOfInner() { (new Outer()).super(); }
}
Perhaps surprisingly, the same instance of Outer
may serve as the immediately enclosing instance of ChildOfInner
with respect to Inner
for multiple instances of ChildOfInner
. These instances of ChildOfInner
are implicitly linked to the same instance of Outer
. The program below achieves this by passing an instance of Outer
to the constructor of ChildOfInner
, which uses the instance in a qualified superclass constructor invocation statement. The rules for an explicit constructor invocation statement do not prohibit using formal parameters of the constructor that contains the statement.
class Outer {
int secret = 5;
class Inner {
int getSecret() { return secret; }
void setSecret(int s) { secret = s; }
}
}
class ChildOfInner extends Outer.Inner {
ChildOfInner(Outer x) { x.super(); }
}
public class Test {
public static void main(String[] args) {
Outer x = new Outer();
ChildOfInner a = new ChildOfInner(x);
ChildOfInner b = new ChildOfInner(x);
System.out.println(b.getSecret());
a.setSecret(6);
System.out.println(b.getSecret());
}
}
This program produces the output:
5
6
The effect is that manipulation of instance variables in the common instance of Outer
is visible through references to different instances of ChildOfInner
, even though such references are not aliases in the conventional sense.
8.9 Enum Types Classes
An enum declaration specifies a new enum type class, a special kind of class type that defines a small set of named class instances.
- EnumDeclaration:
- {ClassModifier}
enum
TypeIdentifier [SuperinterfacesClassImplements] EnumBody
An enum declaration may specify a top level enum class (7.6) or a member enum class (8.5, 9.5).
It is a compile-time error if an enum declaration has the modifier abstract
or final
.
An enum declaration is implicitly final
unless it contains at least one enum constant that has a class body (8.9.1).
A nested member enum type class is implicitly static
. It is permitted for the declaration of a nested member enum type class to redundantly specify the static
modifier.
This implies that it is impossible to declare an enum
typeclassin the body ofas a member of an inner class (8.1.3), because an inner class cannot havestatic
members except for constant variables.
It is a compile-time error if the same keyword appears more than once as a modifier for an enum declaration, or if an enum declaration has more than one of the access modifiers public
, protected
, and private
(6.6).
An enum declaration does not have an extends
clause. The direct superclass type of an enum type class E is Enum<
E>
(8.1.4).
An enum type class has no instances other than those defined by its enum constants. It is a compile-time error to attempt to explicitly instantiate an enum type class (15.9.1).
In addition to the compile-time error, three further mechanisms ensure that no instances of an enum
typeclass exist beyond those defined by its enum constants:
The
final
clone
method inEnum
ensures that enum constants can never be cloned.Reflective instantiation of enum
typesclasses is prohibited.Special treatment by the serialization mechanism ensures that duplicate instances are never created as a result of deserialization.
8.9.1 Enum Constants
The body of an enum declaration may contain enum constants. An enum constant defines an instance of the enum type class.
- EnumBody:
{
[EnumConstantList] [,
] [EnumBodyDeclarations]}
- EnumConstantList:
- EnumConstant {
,
EnumConstant} - EnumConstant:
- {EnumConstantModifier} Identifier [
(
[ArgumentList])
] [ClassBody] - EnumConstantModifier:
- Annotation
The following production from 15.12 is shown here for convenience:
- ArgumentList:
- Expression {
,
Expression}
The rules for annotation modifiers on an enum constant declaration are specified in 9.7.4 and 9.7.5.
The Identifier in a EnumConstant may be used in a name to refer to the enum constant.
The scope and shadowing of an enum constant is specified in 6.3 and 6.4.
An enum constant may be followed by arguments, which are passed to the constructor of the enum when the constant is created during class initialization as described later in this section. The constructor to be invoked is chosen using the normal rules of overload resolution (15.12.2). If the arguments are omitted, an empty argument list is assumed.
The optional class body of an enum constant implicitly defines an anonymous class declaration (15.9.5) that extends the immediately enclosing enum type class. The class body is governed by the usual rules of anonymous classes; in particular it cannot contain any constructors. Instance methods declared in these class bodies may be invoked outside the enclosing enum type class only if they override accessible methods in the enclosing enum type class (8.4.8).
It is a compile-time error for the class body of an enum constant to declare an abstract
method.
This is redundant: anonymous classes are defined to be non-abstract
.
Because there is only one instance of each enum constant, it is permitted to use the ==
operator in place of the equals
method when comparing two object references if it is known that at least one of them refers to an enum constant.
The
equals
method inEnum
is afinal
method that merely invokessuper.equals
on its argument and returns the result, thus performing an identity comparison.
8.9.2 Enum Body Declarations
In addition to enum constants, the body of an enum declaration may contain constructor and member declarations as well as instance and static initializers.
- EnumBodyDeclarations:
;
{ClassBodyDeclaration}
The following productions from 8.1.6 are shown here for convenience:
- ClassBodyDeclaration:
- ClassMemberDeclaration
- InstanceInitializer
- StaticInitializer
- ConstructorDeclaration
- ClassMemberDeclaration:
- FieldDeclaration
- MethodDeclaration
- ClassDeclaration
- InterfaceDeclaration
;
Any constructor or member declarations in the body of an enum declaration apply to the enum type class exactly as if they had been present in the body of a normal class declaration, unless explicitly stated otherwise.
It is a compile-time error if a constructor declaration in an enum declaration is public
or protected
(6.6).
It is a compile-time error if a constructor declaration in an enum declaration contains a superclass constructor invocation statement (8.8.7.1).
It is a compile-time error to refer to a static
field of an enum type class from a constructor, instance initializer, or instance variable initializer of the enum type declaration, unless the field is a constant variable (4.12.4).
In an enum declaration, a constructor declaration with no access modifiers is private
.
In an enum declaration with no constructor declarations, a default constructor is implicitly declared. The default constructor is private
, has no formal parameters, and has no throws
clause.
In practice, a compiler is likely to mirror the
Enum
typeclass by declaringString
andint
parameters in the default constructor of an enumtypeclass. However, these parameters are not specified as "implicitly declared" because different compilers do not need to agree on the form of the default constructor. Only the compiler of an enumtypedeclaration knows how to instantiate the enum constants; other compilers can simply rely on the implicitly declaredpublic
static
fields of the enumtypeclass (8.9.3) without regard for how those fields were initialized.
It is a compile-time error if an enum declaration E has an abstract
method m as a member, unless E has at least one enum constant and all of E's enum constants have class bodies that provide concrete implementations of m.
It is a compile-time error for an enum declaration to declare a finalizer (12.6). An instance of an enum type class may never be finalized.
Example 8.9.2-1. Enum Body Declarations
enum Coin {
PENNY(1), NICKEL(5), DIME(10), QUARTER(25);
Coin(int value) { this.value = value; }
private final int value;
public int value() { return value; }
}
Each enum constant arranges for a different value in the field value
, passed in via a constructor. The field represents the value, in cents, of an American coin. Note that there are no restrictions on the parameters that may be declared by an enum type's class's constructor.
Example 8.9.2-2. Restriction On Enum Constant Self-Reference
Without the rule on static
field access, apparently reasonable code would fail at run time due to the initialization circularity inherent in enum types classes. (A circularity exists in any class with a "self-typed" static
field.) Here is an example of the sort of code that would fail:
import java.util.Map;
import java.util.HashMap;
enum Color {
RED, GREEN, BLUE;
Color() { colorMap.put(toString(), this); }
static final Map<String,Color> colorMap =
new HashMap<String,Color>();
}
Static initialization of this enum would throw a NullPointerException
because the static
variable colorMap
is uninitialized when the constructors for the enum constants run. The restriction above ensures that such code cannot be compiled. However, the code can easily be refactored to work properly:
import java.util.Map;
import java.util.HashMap;
enum Color {
RED, GREEN, BLUE;
static final Map<String,Color> colorMap =
new HashMap<String,Color>();
static {
for (Color c : Color.values())
colorMap.put(c.toString(), c);
}
}
The refactored version is clearly correct, as static initialization occurs top to bottom.
8.9.3 Enum Members
The members of an enum type class E are all of the following:
Members declared in the body of the declaration of E.
Members inherited from
Enum<
E>
.For each enum constant c declared in the body of the declaration of E, E has an implicitly declared
public
static
final
field of type E that has the same name as c. The field has a variable initializer which instantiates E and passes any arguments of c to the constructor chosen for E. The field has the same annotations as c (if any).These fields are implicitly declared in the same order as the corresponding enum constants, before any
static
fields explicitly declared in the body of the declaration of E.An enum constant is said to be created when the corresponding implicitly declared field is initialized.
An implicitly declared method
public
static
E[]
values()
, which returns an array containing the enum constants of E, in the same order as they appear in the body of the declaration of E.An implicitly declared method
public
static
EvalueOf(String name)
, which returns the enum constant of E with the specified name.The following implicitly declared methods:
/** * Returns an array containing the constants of this enum
* type, in the order they're declared. This method may be
* class, in the order they're declared. This method may be
* used to iterate over the constants as follows: * * for(E c : E.values()) * System.out.println(c); * * @return an array containing the constants of this enum
* type, in the order they're declared
* class, in the order they're declared
*/ public static E[] values(); /**
* Returns the enum constant of this type with the specified
* Returns the enum constant of this class with the specified
* name. * The string must match exactly an identifier used to declare
* an enum constant in this type. (Extraneous whitespace
* an enum constant in this class. (Extraneous whitespace
* characters are not permitted.) * * @return the enum constant with the specified name
* @throws IllegalArgumentException if this enum type has no
* @throws IllegalArgumentException if this enum class has no
* constant with the specified name */ public static E valueOf(String name);
It follows that the declaration of enum
typeclass E cannot contain fields that conflict with the implicitly declared fields corresponding to E's enum constants, nor contain methods that conflict with implicitly declared methods or overridefinal
methods of classEnum<
E>
.
Example 8.9.3-1. Iterating Over Enum Constants With An Enhanced for
Loop
public class Test {
enum Season { WINTER, SPRING, SUMMER, FALL }
public static void main(String[] args) {
for (Season s : Season.values())
System.out.println(s);
}
}
This program produces the output:
WINTER
SPRING
SUMMER
FALL
Example 8.9.3-2. Switching Over Enum Constants
A switch
statement (14.11) is useful for simulating the addition of a method to an enum type class from outside the type class. This example "adds" a color
method to the Coin
type class from 8.9.2, and prints a table of coins, their values, and their colors.
class Test {
enum CoinColor { COPPER, NICKEL, SILVER }
static CoinColor color(Coin c) {
switch (c) {
case PENNY:
return CoinColor.COPPER;
case NICKEL:
return CoinColor.NICKEL;
case DIME: case QUARTER:
return CoinColor.SILVER;
default:
throw new AssertionError("Unknown coin: " + c);
}
}
public static void main(String[] args) {
for (Coin c : Coin.values())
System.out.println(c + "\t\t" +
c.value() + "\t" + color(c));
}
}
This program produces the output:
PENNY 1 COPPER
NICKEL 5 NICKEL
DIME 10 SILVER
QUARTER 25 SILVER
Example 8.9.3-3. Enum Constants with Class Bodies
enum Operation {
PLUS {
double eval(double x, double y) { return x + y; }
},
MINUS {
double eval(double x, double y) { return x - y; }
},
TIMES {
double eval(double x, double y) { return x * y; }
},
DIVIDED_BY {
double eval(double x, double y) { return x / y; }
};
// Each constant supports an arithmetic operation
abstract double eval(double x, double y);
public static void main(String args[]) {
double x = Double.parseDouble(args[0]);
double y = Double.parseDouble(args[1]);
for (Operation op : Operation.values())
System.out.println(x + " " + op + " " + y +
" = " + op.eval(x, y));
}
}
Class bodies attach behaviors to the enum constants. The program produces the output:
java Operation 2.0 4.0
2.0 PLUS 4.0 = 6.0
2.0 MINUS 4.0 = -2.0
2.0 TIMES 4.0 = 8.0
2.0 DIVIDED_BY 4.0 = 0.5
This pattern is much safer than using a switch
statement in the base type class (Operation
), as the pattern precludes the possibility of forgetting to add a behavior for a new constant (since the enum declaration would cause a compile-time error).
Example 8.9.3-4. Multiple Enum Types Classes
In the following program, a playing card class is built atop two simple enums.
import java.util.List;
import java.util.ArrayList;
class Card implements Comparable<Card>,
java.io.Serializable {
public enum Rank { DEUCE, THREE, FOUR, FIVE, SIX, SEVEN,
EIGHT, NINE, TEN,JACK, QUEEN, KING, ACE }
public enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES }
private final Rank rank;
private final Suit suit;
public Rank rank() { return rank; }
public Suit suit() { return suit; }
private Card(Rank rank, Suit suit) {
if (rank == null || suit == null)
throw new NullPointerException(rank + ", " + suit);
this.rank = rank;
this.suit = suit;
}
public String toString() { return rank + " of " + suit; }
// Primary sort on suit, secondary sort on rank
public int compareTo(Card c) {
int suitCompare = suit.compareTo(c.suit);
return (suitCompare != 0 ?
suitCompare :
rank.compareTo(c.rank));
}
private static final List<Card> prototypeDeck =
new ArrayList<Card>(52);
static {
for (Suit suit : Suit.values())
for (Rank rank : Rank.values())
prototypeDeck.add(new Card(rank, suit));
}
// Returns a new deck
public static List<Card> newDeck() {
return new ArrayList<Card>(prototypeDeck);
}
}
The following program exercises the Card
class. It takes two integer parameters on the command line, representing the number of hands to deal and the number of cards in each hand:
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
class Deal {
public static void main(String args[]) {
int numHands = Integer.parseInt(args[0]);
int cardsPerHand = Integer.parseInt(args[1]);
List<Card> deck = Card.newDeck();
Collections.shuffle(deck);
for (int i=0; i < numHands; i++)
System.out.println(dealHand(deck, cardsPerHand));
}
/**
* Returns a new ArrayList consisting of the last n
* elements of deck, which are removed from deck.
* The returned list is sorted using the elements'
* natural ordering.
*/
public static <E extends Comparable<E>>
ArrayList<E> dealHand(List<E> deck, int n) {
int deckSize = deck.size();
List<E> handView = deck.subList(deckSize - n, deckSize);
ArrayList<E> hand = new ArrayList<E>(handView);
handView.clear();
Collections.sort(hand);
return hand;
}
}
The program produces the output:
java Deal 4 3
[DEUCE of CLUBS, SEVEN of CLUBS, QUEEN of DIAMONDS]
[NINE of HEARTS, FIVE of SPADES, ACE of SPADES]
[THREE of HEARTS, SIX of HEARTS, TEN of SPADES]
[TEN of CLUBS, NINE of DIAMONDS, THREE of SPADES]
Chapter 9: Interfaces
An interface declaration introduces a new reference type interface whose members are classes, interfaces, constants, and methods that can be implemented by one or more classes. Programs can use interfaces to provide a common supertype for otherwise-unrelated classes.
This type has Interfaces have no instance variables, and typically declares declare one or more abstract
methods; otherwise unrelated classes can implement the an interface by providing implementations for its abstract
methods. Interfaces may not be directly instantiated.
A nested interface is any interface whose declaration occurs within the body of another class or interface.
A top level interface is an interface that is not a nested interface.
A top level interface (7.6) is an interface that is declared at the top level of a compilation unit.
A nested interface is any interface whose declaration occurs as a member interface (8.5, 9.5) of another class or interface.
We distinguish between two kinds of interfaces - normal interfaces and annotation types.
An annotation interface (9.6) is an interface declared with special syntax, intended to be implemented by reflective representations of annotations (9.7).
This chapter discusses the common semantics of all interfaces - normal interfaces, both top level (7.6) and nested (8.5, 9.5), and annotation types (9.6). Details that are specific to particular kinds of interfaces are discussed in the sections dedicated to these constructs.
Programs can use interfaces to make it unnecessary for related classes to share a common abstract
superclass or to add methods to Object
.
An interface may be declared to be a direct extension of one or more other interfaces, meaning that it inherits all the member types classes and interfaces, instance methods, and constants static
fields of the interfaces it extends, except for any members that it may override or hide.
A class may be declared to directly implement one or more interfaces (8.1.5), meaning that any instance of the class implements all the abstract
methods specified by the interface or interfaces. A class necessarily implements all the interfaces that its direct superclasses and direct superinterfaces do. This (multiple) interface inheritance allows objects to support (multiple) common behaviors without sharing a superclass.
A variable whose declared type is an interface type may have as its value a reference to any instance of a class which implements the specified interface. It is not sufficient that the class happen to implement all the abstract
methods of the interface; the class or one of its superclasses must actually be declared to implement the interface, or else the class is not considered to implement the interface.
9.1 Interface Declarations
An interface declaration specifies a new named reference type an interface. There are two kinds of interface declarations - normal interface declarations and annotation type interface declarations (9.6).
- InterfaceDeclaration:
- NormalInterfaceDeclaration
- AnnotationTypeDeclaration
- NormalInterfaceDeclaration:
- {InterfaceModifier}
interface
TypeIdentifier [TypeParameters]
[ExtendsInterfacesInterfaceExtends] InterfaceBody
The term ExtendsInterfaces incorrectly suggests that the production is a list of interfaces, not interface types. The term InterfaceExtends is aligned with ClassExtends from 8.1.
The TypeIdentifier in an interface declaration specifies the name of the interface.
It is a compile-time error if an interface has the same simple name as any of its enclosing classes or interfaces.
The scope and shadowing of an interface declaration is specified in 6.3 and 6.4.
9.1.1 Interface Modifiers
An interface declaration may include interface modifiers.
- InterfaceModifier:
- (one of)
- Annotation
public
protected
private
abstract
static
strictfp
The rules for annotation modifiers on an interface declaration are specified in 9.7.4 and 9.7.5.
The access modifier public
(6.6) pertains to every kind of interface declaration.
So do abstract
and strictfp
. Why single this one out?
The access modifiers protected
, and private
, and static
pertain only to member interfaces (8.5, 9.5) whose declarations are directly enclosed by a class declaration (8.5.1).
The modifier static
pertains only to member interfaces (8.5.1, 9.5), not to top level interfaces (7.6).
Compare changes to 8.1.1.
It is a compile-time error if the same keyword appears more than once as a modifier for an interface declaration, or if a interface declaration has more than one of the access modifiers public
, protected
, and private
(6.6).
If two or more (distinct) interface modifiers appear in an interface declaration, then it is customary, though not required, that they appear in the order consistent with that shown above in the production for InterfaceModifier.
9.1.3 Superinterfaces and Subinterfaces
The core feature being described here is an interface's set of superinterfaces. "Subinterfaces" is merely a convenient bit of terminology, not significant enough to belong in the title.
If an extends
clause is provided, then the interface being declared extends each of the other named interfaces listed interface types and therefore inherits the member types classes and interfaces, instance methods, and constants of each of the other named interfaces listed interface types.
These other named interfaces listed interface types are the direct superinterfaces superinterface types of the interface being declared.
Any class that implements
the declared interface is also considered to implement all the interfaces that this interface extends
.
This is covered by 8.1.5. Here, "considered to implement" is a vague thing to say.
ExtendsInterfaces:InterfaceExtends:extends
InterfaceTypeList
The following production from 8.1.5 is shown here for convenience:
- InterfaceTypeList:
- InterfaceType {
,
InterfaceType}
Each InterfaceType in the extends
clause of an interface declaration must name an accessible interface type (6.6), or a compile-time error occurs.
If an InterfaceType has type arguments, it must denote a well-formed parameterized type (4.5), and none of the type arguments may be wildcard type arguments, or a compile-time error occurs.
Given a (possibly generic) interface declaration I<
F1,...,Fn>
(n ≥ 0), the direct superinterfaces of the interface type I<
F1,...,Fn>
are the types given in the extends
clause of the declaration of I, if an extends
clause is present.
Given a generic interface declaration I<
F1,...,Fn>
(n > 0), the direct superinterfaces of the parameterized interface type I<
T1,...,Tn>
, where Ti (1 ≤ i ≤ n) is a type, are all types J<
U1 θ,...,Uk θ>
, where J<
U1,...,Uk>
is a direct superinterface of I<
F1,...,Fn>
and θ is the substitution [F1:=T1,...,Fn:=Tn]
.
Covered by 4.10.2. This section is only concerned with the superinterface types of an interface, not the superinterface types of types.
The direct superinterface type of an annotation interface is, implicitly, java.lang.annotation.Annotation
.
One interface is a direct superinterface of another interface if the first interface is named by one of the direct superinterface types of the second interface.
The superinterface relationship is the transitive closure of the direct superinterface relationship. An interface K is a superinterface of interface I if either of the following is true:
K is a direct superinterface of I.
There exists an interface J such thatWhere J is a direct superinterface of I, K is a superinterface of J,and J is a superinterface of I,applying this definition recursively.
Interface I is said to be a subinterface of interface K whenever K is a superinterface of I. An interface is said to be a direct subinterface of its direct superinterface, and a subinterface of each of its superinterfaces.
While every class is an extension of class Object
, there is no single interface of which all interfaces are extensions.
An interface I directly depends on a type T class or interface A if T A is mentioned in the extends
clause of I either as a superinterface or as a qualifier in the fully qualified form of a superinterface name.
An interface I depends on a reference type T class or interface A if any of the following is true:
I directly depends on
TA.I directly depends on a class C that depends on
TA (8.1.5).I directly depends on an interface J that depends on
TA (using this definition recursively).
It is a compile-time error if an interface depends on itself.
If circularly declared interfaces are detected at run time, as interfaces are loaded, then a ClassCircularityError
is thrown (12.2.1).
9.1.4 Interface Body and Member Declarations
The body of an interface may declare members of the interface, that is, fields (9.3), methods (9.4), classes (9.5), and interfaces (9.5).
- InterfaceBody:
{
{InterfaceMemberDeclaration}}
- InterfaceMemberDeclaration:
- ConstantDeclaration
- InterfaceMethodDeclaration
- ClassDeclaration
- InterfaceDeclaration
;
The scope of a declaration of a member m declared in or inherited by an interface type I is specified in 6.3.
9.2 Interface Members
The members of an interface type are:
Members declared in the body of the interface (9.1.4).
Members inherited from any direct
superinterfacessuperinterface types (9.1.3).If an interface has no direct
superinterfacessuperinterface types, then the interface implicitly declares apublic
abstract
member method m with signature s, return type r, andthrows
clause t corresponding to eachpublic
instance method m with signature s, return type r, andthrows
clause t declared inObject
(4.3.2), unless anabstract
method with the same signature, same return type, and a compatiblethrows
clause is explicitly declared by the interface.It is a compile-time error if the interface explicitly declares such a method m in the case where m is declared to be
final
inObject
.It is a compile-time error if the interface explicitly declares a method with a signature that is override-equivalent (8.4.2) to a
public
method ofObject
, but which has a different return type, or an incompatiblethrows
clause, or is notabstract
.
The interface inherits, from the interfaces it extends, all members of those interfaces, except for (i) fields, classes, and interfaces that it hides, (ii) abstract
methods and default methods that it overrides (9.4.1), (iii) private
methods, and (iv) static
methods.
Fields, methods, and member types classes and interfaces of an interface type may have the same name, since they are used in different contexts and are disambiguated by different lookup procedures (6.5). However, this is discouraged as a matter of style.
9.4 Method Declarations
9.4.1 Inheritance and Overriding
An interface I inherits from its direct superinterfaces superinterface types all abstract
and default methods m for which all of the following are true:
m is a member of a direct superinterface type, J, of I.
No method declared in I has a signature that is a subsignature (8.4.2) of the signature of m as a member of J.
There exists no method m' that is a member of a direct superinterface type, J', of I (m distinct from m', J distinct from J'), such that m' overrides from the interface of J' the declaration of the method m.
Note that methods are overridden on a signature-by-signature basis. If, for example, an interface declares two
public
methods with the same name (9.4.2), and a subinterface overrides one of them, the subinterface still inherits the other method.
The third clause above prevents a subinterface from re-inheriting a method that has already been overridden by another of its superinterfaces. For example, in this program:
interface Top { default String name() { return "unnamed"; } } interface Left extends Top { default String name() { return getClass().getName(); } } interface Right extends Top {} interface Bottom extends Left, Right {}
Right
inheritsname()
fromTop
, butBottom
inheritsname()
fromLeft
, notRight
. This is becausename()
fromLeft
overrides the declaration ofname()
inTop
.
An interface does not inherit private
or static
methods from its superinterfaces.
If an interface I declares a private
or static
method m, and the signature of m is a subsignature of a public
instance method m' in a superinterface type of I, and m' would otherwise be accessible to code in I, then a compile-time error occurs.
In essence, a
static
method in an interface cannot hide an instance method in a superinterface type. This is similar to the rule in 8.4.8.2 whereby astatic
method in a class cannot hide an instance method in a superclass type or superinterface type. Note that the rule in 8.4.8.2 speaks of a class that "declares or inherits astatic
method", whereas the rule above speaks only of an interface that "declares astatic
method", since an interface cannot inherit astatic
method. Also note that the rule in 8.4.8.2 allows hiding of both instance andstatic
methods in superclasses/superinterfaces, whereas the rule above considers onlypublic
instance methods insuperinterfacessuperinterface types.
Along the same lines, a
private
method in an interface cannot override an instance method - whetherpublic
orprivate
- in a superinterface type. This is similar to the rules in 8.4.8.1 and 8.4.8.3 whereby aprivate
method in a class cannot override any instance method in a superclass type or superinterface type, because 8.4.8.1 requires the overridden method to be non-private
and 8.4.8.3 requires the overriding method to provide at least as much access as the overridden method. In summary, onlypublic
methods in interfaces can be overridden, and only bypublic
methods in subinterfaces or in implementing classes.
9.4.1.1 Overriding (by Instance Methods)
An instance method mI declared in or inherited by interface I, overrides from I another instance method mJ declared in interface J, iff all of the following are true:
I is a subinterface of J.
I does not inherit mJ.
The signature of mI is a subsignature (8.4.2) of the signature of mJ as a member of the supertype of I that names J.
mJ is
public
.
The presence or absence of the strictfp
modifier has absolutely no effect on the rules for overriding methods. For example, it is permitted for a method that is not FP-strict to override an FP-strict method and it is permitted for an FP-strict method to override a method that is not FP-strict.
An overridden default method can be accessed by using a method invocation expression (15.12) that contains the keyword
super
qualified by a superinterface name.
9.5 Member Type Class and Interface Declarations
Interfaces may contain member type class and interface declarations (8.5).
Every member type class or interface declaration in the body of an interface is implicitly public
and static
. It is permitted to redundantly specify either or both of these modifiers.
It is a compile-time error if a member type class or interface declaration in an interface has the modifier protected
or private
.
It is a compile-time error if the same keyword appears more than once as a modifier for a member type declaration in an interface.
If an interface declares a member type class or interface with a certain name, then the declaration of that type class or interface is said to hide any and all accessible declarations of member types classes and interfaces with the same name in superinterfaces of the interface.
An interface inherits from its direct superinterfaces all the non- member private
types classes and interfaces of the superinterfaces that are both accessible to code in the interface and not hidden by a declaration in the interface.
All member classes and interfaces of the superinterfaces are public
, so we don't need to consider their acccessibility here.
It is possible for an interface to inherit more than one member type class or interface with the same name. Such a situation does not in itself cause a compile-time error. However, any attempt within the body of the interface to refer to any such member type class or interface by its simple name will result in a compile-time error, because the reference is ambiguous.
There might be several paths by which the same member type class or interface declaration is inherited from an interface. In such a situation, the member type class or interface is considered to be inherited only once, and it may be referred to by its simple name without ambiguity.
9.6 Annotation Types Interfaces
An annotation type declaration specifies a new annotation type interface, a special kind of interface type. To distinguish an annotation type declaration from a normal interface declaration, the keyword interface
is preceded by an at-sign at sign (@
).
AnnotationTypeDeclaration:AnnotationDeclaration:- {InterfaceModifier}
@
interface
TypeIdentifierAnnotationTypeBodyAnnotationInterfaceBody
Note that the
at-signat sign (@
) and the keywordinterface
are distinct tokens. It is possible to separate them with whitespace, but this is discouraged as a matter of style.
The rules for annotation modifiers on an annotation type declaration are specified in 9.7.4 and 9.7.5.
The TypeIdentifier in an annotation type declaration specifies the name of the annotation type interface.
It is a compile-time error if an annotation type interface has the same simple name as any of its enclosing classes or interfaces.
The direct superinterface type of every annotation type interface is java.lang.annotation.Annotation
(9.1.3).
By virtue of the
AnnotationTypeDeclarationAnnotationInterfaceDeclaration syntax, an annotationtypeinterface declaration cannot be generic, and noextends
clause is permitted.
A consequence of the fact that an annotation
typeinterface cannot explicitly declare a superclass type or superinterface type is that asubclass orsubinterface of an annotationtypeinterface is never itself an annotationtypeinterface. Similarly,java.lang.annotation.Annotation
is not itself an annotationtypeinterface.
An annotation type interface inherits several members from java.lang.annotation.Annotation
, including the implicitly declared methods corresponding to the instance methods of Object
, yet these methods do not define elements of the annotation type interface (9.6.1).
Because these methods do not define elements of the annotation
typeinterface, it is illegal to use them in annotations of that type (9.7). Without this rule, we could not ensure that elements were of the types representable in annotations, or that accessor methods for them would be available.
Unless explicitly modified herein, all of the rules that apply to normal interface declarations apply to annotation type declarations.
For example, annotation
typesinterfaces share the same namespace as normalclass and interface typesclasses and interfaces; and annotationtypedeclarationsare legal wherever interface declarations are legal, andhave the same scope and accessibility as interface declarations.
9.6.1 Annotation Type Elements
The body of an annotation type declaration may contain method declarations, each of which defines an element of the annotation type interface. An annotation type interface has no elements other than those defined by the methods it explicitly declares.
AnnotationTypeBody:AnnotationInterfaceBody:{
{AnnotationTypeMemberDeclarationAnnotationMemberDeclaration }}
AnnotationTypeMemberDeclaration:AnnotationMemberDeclaration:AnnotationTypeElementDeclarationAnnotationElementDeclaration- ConstantDeclaration
- ClassDeclaration
- InterfaceDeclaration
;
AnnotationTypeElementDeclaration:AnnotationElementDeclaration:- {
AnnotationTypeElementModifierAnnotationElementModifier } UnannType Identifier(
)
[Dims]
[DefaultValue];
AnnotationTypeElementModifier:AnnotationElementModifier:- (one of)
- Annotation
public
abstract
By virtue of the
AnnotationTypeElementDeclarationAnnotationElementDeclaration production, a method declaration in an annotationtypedeclaration cannot have formal parameters, type parameters, or athrows
clause. The following production from 4.3 is shown here for convenience:
- Dims:
- {Annotation}
[
]
{{Annotation}[
]
}
By virtue of the
AnnotationTypeElementModifierAnnotationElementModifier production, a method declaration in an annotationtypedeclaration cannot bedefault
orstatic
. Thus, an annotationtypeinterface cannot declare the same variety of methods as a normal interfacetype. Note that it is still possible for an annotationtypeinterface to inherit a default method from its implicit superinterface,java.lang.annotation.Annotation
, though no such default method exists as of Java SE 14.
By convention, the only
AnnotationTypeElementModifiersAnnotationElementModifiers that should be present on an annotationtypeelement declaration are annotations.
The return type of a method declared in an annotation type interface must be one of the following, or a compile-time error occurs:
A primitive type
String
Class
or an invocation ofClass
(4.5)An enum class type
An annotation interface type
An array type whose component type is one of the preceding types (10.1).
This rule precludes elements with nested array types, such as:
@interface Verboten { String[][] value(); }
The declaration of a method that returns an array is allowed to place the bracket pair that denotes the array type after the empty formal parameter list. This syntax is supported for compatibility with early versions of the Java programming language. It is very strongly recommended that this syntax is not used in new code.
It is a compile-time error if any method declared in an annotation type interface has a signature that is override-equivalent to that of any public
or protected
method declared in class Object
or in the interface java.lang.annotation.Annotation
.
It is a compile-time error if an annotation type declaration a declaration of an annotation interface T contains an element of type T, either directly or indirectly.
For example, this is illegal:
@interface SelfRef { SelfRef value(); }
and so is this:
@interface Ping { Pong value(); } @interface Pong { Ping value(); }
An annotation type interface with no elements is called a marker annotation type interface.
An annotation type interface with one element is called a single-element annotation type interface.
By convention, the name of the sole element in a single-element annotation type interface is value
. Linguistic support for this convention is provided by single-element annotations (9.7.3).
Example 9.6.1-1. Annotation Type Declaration
The following annotation type declaration defines an annotation type interface with several elements:
/**
* Describes the "request-for-enhancement" (RFE)
* that led to the presence of the annotated API element.
*/
@interface RequestForEnhancement {
int id(); // Unique ID number associated with RFE
String synopsis(); // Synopsis of RFE
String engineer(); // Name of engineer who implemented RFE
String date(); // Date RFE was implemented
}
Example 9.6.1-2. Marker Annotation Type Declaration
The following annotation type declaration defines a marker annotation type interface:
/**
* An annotation with this type indicates that the
* specification of the annotated API element is
* preliminary and subject to change.
*/
@interface Preliminary {}
Example 9.6.1-3. Single-Element Annotation Type Declarations
The convention that a single-element annotation type interface defines an element called value
is illustrated in the following annotation type declaration:
/**
* Associates a copyright notice with the annotated API element.
*/
@interface Copyright {
String value();
}
The following annotation type declaration defines a single-element annotation type interface whose sole element has an array type:
/**
* Associates a list of endorsers with the annotated class.
*/
@interface Endorsers {
String[] value();
}
The following annotation type declaration shows a Class
-typed element whose value is constrained by a bounded wildcard:
interface Formatter {}
// Designates a formatter to pretty-print the annotated class
@interface PrettyPrinter {
Class<? extends Formatter> value();
}
The following annotation type declaration contains an element whose type is also an annotation interface type:
/**
* Indicates the author of the annotated program element.
*/
@interface Author {
Name value();
}
/**
* A person's name. This annotation type is not designed
* to be used directly to annotate program elements, but to
* define elements of other annotation types.
* A person's name. This annotation interface is not designed
* to be used directly to annotate program elements, but to
* define elements of other annotation interfaces.
*/
@interface Name {
String first();
String last();
}
The grammar for annotation type declarations permits other element member declarations besides method element declarations. For example, one might choose to declare a nested enum for use in conjunction with an annotation type interface:
@interface Quality {
enum Level { BAD, INDIFFERENT, GOOD }
Level value();
}
9.6.2 Defaults for Annotation Type Elements
An annotation type element declaration may have a default value, specified by following the element's (empty) parameter list with the keyword default
and an ElementValue (9.7.1).
- DefaultValue:
default
ElementValue
It is a compile-time error if the type of the element is not commensurate (9.7) with the default value specified.
Default values are not compiled into annotations, but rather applied dynamically at the time annotations are read. Thus, changing a default value affects annotations even in classes that were compiled before the change was made (presuming these annotations lack an explicit value for the defaulted element).
Example 9.6.2-1. Annotation Type Declaration With Default Values
Here is a refinement of the RequestForEnhancement
annotation type interface from 9.6.1:
@interface RequestForEnhancementDefault {
int id(); // No default - must be specified in
// each annotation
String synopsis(); // No default - must be specified in
// each annotation
String engineer() default "[unassigned]";
String date() default "[unimplemented]";
}
9.6.3 Repeatable Annotation Types Interfaces
An annotation type T interface A is repeatable if its declaration is (meta-)annotated with an @Repeatable
annotation (9.6.4.8) whose value
element indicates a containing annotation type interface of T A.
An annotation type TC interface AC is a containing annotation type interface of T A if all of the following are true:
TCAC declares avalue()
methodelement whose return type isTA[]
[]
.Any
methodselements declared byTCAC other thanvalue()
have a default value.TCAC is retained for at least as long asTA, where retention is expressed explicitly or implicitly with the@Retention
annotation (9.6.4.2). Specifically:If the retention of
TCAC isjava.lang.annotation.RetentionPolicy.SOURCE
, then the retention ofTA isjava.lang.annotation.RetentionPolicy.SOURCE
.If the retention of
TCAC isjava.lang.annotation.RetentionPolicy.CLASS
, then the retention ofTA is eitherjava.lang.annotation.RetentionPolicy.CLASS
orjava.lang.annotation.RetentionPolicy.SOURCE
.If the retention of
TCAC isjava.lang.annotation.RetentionPolicy.RUNTIME
, then the retention ofTA isjava.lang.annotation.RetentionPolicy.SOURCE
,java.lang.annotation.RetentionPolicy.CLASS
, orjava.lang.annotation.RetentionPolicy.RUNTIME
.
TA is applicable to at least the same kinds of program element asTCAC (9.6.4.1). Specifically, if the kinds of program element whereTA is applicable are denoted by the set m1, and the kinds of program element whereTCAC is applicable are denoted by the set m2, then each kind in m2 must occur in m1, except that:If the kind in m2 is
java.lang.annotation.ElementType.ANNOTATION_TYPE
, then at least one ofjava.lang.annotation.ElementType.ANNOTATION_TYPE
orjava.lang.annotation.ElementType.TYPE
orjava.lang.annotation.ElementType.TYPE_USE
must occur in m1.If the kind in m2 is
java.lang.annotation.ElementType.TYPE
, then at least one ofjava.lang.annotation.ElementType.TYPE
orjava.lang.annotation.ElementType.TYPE_USE
must occur in m1.If the kind in m2 is
java.lang.annotation.ElementType.TYPE_PARAMETER
, then at least one ofjava.lang.annotation.ElementType.TYPE_PARAMETER
orjava.lang.annotation.ElementType.TYPE_USE
must occur in m1.
This clause implements the policy that an annotation
typeinterface may be repeatable on only some of the kinds of program element where it is applicable.If the declaration of
TA has a (meta-)annotation that corresponds tojava.lang.annotation.Documented
, then the declaration ofTCAC must have a (meta-)annotation that corresponds tojava.lang.annotation.Documented
.Note that it is permissible for
TCAC to be@Documented
whileTA is not@Documented
.If the declaration of
TA has a (meta-)annotation that corresponds tojava.lang.annotation.Inherited
, then the declaration ofTCAC must have a (meta)-annotation that corresponds tojava.lang.annotation.Inherited
.Note that it is permissible for
TCAC to be@Inherited
whileTA is not@Inherited
.
It is a compile-time error if an annotation type T interface A is (meta-)annotated with an @Repeatable
annotation whose value
element indicates a type which is not a containing annotation type interface of T.
Example 9.6.3-1. Ill-formed Containing Annotation Type Interface
Consider the following declarations:
import java.lang.annotation.Repeatable;
@Repeatable(FooContainer.class)
@interface Foo {}
@interface FooContainer { Object[] value(); }
Compiling the Foo
declaration produces a compile-time error because Foo
uses @Repeatable
to attempt to specify FooContainer
as its containing annotation type interface, but FooContainer
is not in fact a containing annotation type interface of Foo
. (The return type of FooContainer.value()
is not Foo[]
.)
The @Repeatable
annotation cannot be repeated, so only one containing annotation type interface can be specified by a repeatable annotation type interface.
Allowing more than one containing annotation
typeinterface to be specified would cause an undesirable choice at compile time, when multiple annotations of the repeatable annotationtypeinterface are logically replaced with a container annotation (9.7.5).
An annotation type interface can be the containing annotation type interface of at most one annotation type interface.
This is implied by the requirement that if the declaration of an annotation
type Tinterface A specifies a containing annotationtypeinterface ofTCAC, then thevalue()
method ofTCAC has a return type involvingTA, specificallyTA[]
[]
.
An annotation type interface cannot specify itself as its containing annotation type interface.
This is implied by the requirement on the
value()
method of the containing annotationtypeinterface. Specifically, if an annotationtypeinterface A specified itself (via@Repeatable
) as its containing annotationtypeinterface, then the return type of A'svalue()
method would have to be A[]
; but this would cause a compile-time error since an annotationtypeinterface cannot refer to itself in its elements (9.6.1). More generally, two annotationtypesinterfaces cannot specify each other to be their containing annotationtypesinterfaces, because cyclic annotationtypeinterface declarations are illegal.
An annotation type TC interface AC may be the containing annotation type interface of some annotation type T interface A while also having its own containing annotation type TC ' interface AC '. That is, a containing annotation type interface may itself be a repeatable annotation type interface.
Example 9.6.3-2. Restricting Where Annotations May Repeat
An annotation whose type declaration indicates a target of java.lang.annotation.ElementType.TYPE
can appear in at least as many locations as an annotation whose type declaration indicates a target of java.lang.annotation.ElementType.ANNOTATION_TYPE
. For example, given the following declarations of repeatable and containing annotation types interfaces:
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
import java.lang.annotation.Repeatable;
@Target(ElementType.TYPE)
@Repeatable(FooContainer.class)
@interface Foo {}
@Target(ElementType.ANNOTATION_TYPE)
@interface FooContainer {
Foo[] value();
}
@Foo
can appear on any type class or interface declaration while @FooContainer
can appear on only annotation type interface declarations. Therefore, the following annotation type interface declaration is legal:
@Foo @Foo
@interface Anno {}
while the following interface declaration is illegal:
@Foo @Foo
interface Intf {}
More broadly, if Foo
is a repeatable annotation type interface and FooContainer
is its containing annotation type interface, then:
If
Foo
has no@Target
meta-annotation andFooContainer
has no@Target
meta-annotation, then@Foo
may be repeated on any program element which supports annotations.If
Foo
has no@Target
meta-annotation butFooContainer
has an@Target
meta-annotation, then@Foo
may only be repeated on program elements where@FooContainer
may appear.If
Foo
has an@Target
meta-annotation, then in the judgment of the designers of the Java programming language,FooContainer
must be declared with knowledge of theFoo
's applicability. Specifically, the kinds of program element whereFooContainer
may appear must logically be the same as, or a subset of,Foo
's kinds.For example, if
Foo
is applicable to field and method declarations, thenFooContainer
may legitimately serve asFoo
's containing annotationtypeinterface ifFooContainer
is applicable to just field declarations (preventing@Foo
from being repeated on method declarations). But ifFooContainer
is applicable only to formal parameter declarations, thenFooContainer
was a poor choice of containing annotationtypeinterface byFoo
because@FooContainer
cannot be implicitly declared on some program elements where@Foo
is repeated.Similarly, if
Foo
is applicable to field and method declarations, thenFooContainer
cannot legitimately serve asFoo
's containing annotationtypeinterface ifFooContainer
is applicable to field and parameter declarations. While it would be possible to take the intersection of the program elements and makeFoo
repeatable on field declarations only, the presence of additional program elements forFooContainer
indicates thatFooContainer
was not designed as a containing annotationtypeinterface forFoo
. It would therefore be dangerous forFoo
to rely on it.
Example 9.6.3-3. A Repeatable Containing Annotation Type Interface
The following declarations are legal:
import java.lang.annotation.Repeatable;
// Foo: Repeatable annotation type
// Foo: Repeatable annotation interface
@Repeatable(FooContainer.class)
@interface Foo { int value(); }
// FooContainer: Containing annotation type of Foo
// Also a repeatable annotation type itself
// FooContainer: Containing annotation interface of Foo
// Also a repeatable annotation interface itself
@Repeatable(FooContainerContainer.class)
@interface FooContainer { Foo[] value(); }
// FooContainerContainer: Containing annotation type of FooContainer
// FooContainerContainer: Containing annotation interface of FooContainer
@interface FooContainerContainer { FooContainer[] value(); }
Thus, an annotation whose type interface is a containing annotation type interface may itself be repeated:
@FooContainer({@Foo(1)}) @FooContainer({@Foo(2)})
class Test {}
An annotation type interface which is both repeatable and containing is subject to the rules on mixing annotations of a repeatable annotation type interface with annotations of a containing annotation type interface (9.7.5). For example, it is not possible to write multiple @Foo
annotations alongside multiple @FooContainer
annotations, nor is it possible to write multiple @FooContainer
annotations alongside multiple @FooContainerContainer
annotations. However, if the FooContainerContainer
type annotation interface was itself repeatable, then it would be possible to write multiple @Foo
annotations alongside multiple @FooContainerContainer
annotations.
9.6.4 Predefined Annotation Types Interfaces
Several annotation types interfaces are predefined in the libraries of the Java SE Platform. Some of these predefined annotation types interfaces have special semantics. These semantics are specified in this section. This section does not provide a complete specification for the predefined annotations contained here in; that is the role of the appropriate API specifications. Only those semantics that require special behavior on the part of a Java compiler or Java Virtual Machine implementation are specified here.
9.6.4.1 @Target
An annotation of type java.lang.annotation.Target
is used on the declaration of an annotation type interface T to specify the contexts in which T is applicable. java.lang.annotation.Target
has a single element, value
, of type java.lang.annotation.ElementType[]
, to specify contexts.
Annotation types interfaces may be applicable in declaration contexts, where annotations apply to declarations, or in type contexts, where annotations apply to types used in declarations and expressions.
There are nine declaration contexts, each corresponding to an enum constant of java.lang.annotation.ElementType
:
Module declarations (7.7)
Corresponds to
java.lang.annotation.ElementType.MODULE
Package declarations (7.4.1)
Corresponds to
java.lang.annotation.ElementType.PACKAGE
Type declarations: class, interface, enum, and annotation
typedeclarations (8.1.1, 9.1.1, 8.5, 9.5, 8.9, 9.6)Corresponds to
java.lang.annotation.ElementType.TYPE
Additionally, annotation
typedeclarations correspond tojava.lang.annotation.ElementType.ANNOTATION_TYPE
Method declarations (including elements of annotation
typesinterfaces) (8.4.3, 9.4, 9.6.1)Corresponds to
java.lang.annotation.ElementType.METHOD
Constructor declarations (8.8.3)
Corresponds to
java.lang.annotation.ElementType.CONSTRUCTOR
Type parameter declarations of generic classes, interfaces, methods, and constructors (8.1.2, 9.1.2, 8.4.4, 8.8.4)
Corresponds to
java.lang.annotation.ElementType.TYPE_PARAMETER
Field declarations (including enum constants) (8.3.1, 9.3, 8.9.1)
Corresponds to
java.lang.annotation.ElementType.FIELD
Formal and exception parameter declarations (8.4.1, 9.4, 14.20)
Corresponds to
java.lang.annotation.ElementType.PARAMETER
Local variable declarations (including loop variables of
for
statements and resource variables oftry
-with-resources statements) (14.4, 14.14.1, 14.14.2, 14.20.3)Corresponds to
java.lang.annotation.ElementType.LOCAL_VARIABLE
There are 16 type contexts (4.11), all represented by the enum constant TYPE_USE
of java.lang.annotation.ElementType
.
It is a compile-time error if the same enum constant appears more than once in the value
element of an annotation of type java.lang.annotation.Target
.
If an annotation of type java.lang.annotation.Target
is not present on the declaration of an annotation type interface T, then T is applicable in all nine declaration contexts and in all 16 type contexts.
9.6.4.2 @Retention
Annotations may be present only in source code, or they may be present in the binary form of a class or interface. An annotation that is present in the binary form may or may not be available at run time via the reflection libraries of the Java SE Platform. The annotation type interface java.lang.annotation.Retention
is used to choose among these possibilities.
If an annotation a corresponds to a type an annotation interface T, and T has a (meta-)annotation m that corresponds to java.lang.annotation.Retention
, then:
If m has an element whose value is
java.lang.annotation.RetentionPolicy.SOURCE
, then a Java compiler must ensure that a is not present in the binary representation of the class or interface in which a appears.If m has an element whose value is
java.lang.annotation.RetentionPolicy.CLASS
orjava.lang.annotation.RetentionPolicy.RUNTIME
, then a Java compiler must ensure that a is represented in the binary representation of the class or interface in which a appears, unless a annotates a local variable declaration or a annotates a formal parameter declaration of a lambda expression.An annotation on the declaration of a local variable, or on the declaration of a formal parameter of a lambda expression, is never retained in the binary representation. In contrast, an annotation on the type of a local variable, or on the type of a formal parameter of a lambda expression, is retained in the binary representation if the annotation
typeinterface specifies a suitable retention policy.Note that it is not illegal for an annotation
typeinterface to be meta-annotated with@Target(java.lang.annotation.ElementType.LOCAL_VARIABLE)
and@Retention(java.lang.annotation.RetentionPolicy.CLASS)
or@Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
.If m has an element whose value is
java.lang.annotation.RetentionPolicy.RUNTIME
, the reflection libraries of the Java SE Platform must make a available at run time.
If T does not have a (meta-)annotation m that corresponds to java.lang.annotation.Retention
, then a Java compiler must treat T as if it does have such a meta-annotation m with an element whose value is java.lang.annotation.RetentionPolicy.CLASS
.
9.6.4.3 @Inherited
The annotation type interface java.lang.annotation.Inherited
is used to indicate that annotations on a class C corresponding to a given annotation type interface are inherited by subclasses of C.
9.6.4.4 @Override
Programmers occasionally overload a method declaration when they mean to override it, leading to subtle problems. The annotation type interface Override
supports early detection of such problems.
The classic example concerns the
equals
method. Programmers write the following in classFoo
:public boolean equals(Foo that) { ... }
when they mean to write:
public boolean equals(Object that) { ... }
This is perfectly legal, but class
Foo
inherits theequals
implementation fromObject
, which can cause some subtle bugs.
If a method declaration in type class or interface T is annotated with @Override
, but the method does not override from T a method declared in a supertype of T (8.4.8.1, 9.4.1.1), or is not override-equivalent to a public
method of Object
(4.3.2, 8.4.2), then a compile-time error occurs.
This behavior differs from Java SE 5.0, where
@Override
only caused a compile-time error if applied to a method that implemented a method from a superinterface that was not also present in a superclass.
The clause about overriding a
public
method is motivated by use of@Override
in an interface. Consider the followingtypedeclarations:class Foo { @Override public int hashCode() {..} } interface Bar { @Override int hashCode(); }
The use of
@Override
in the class declaration is legal by the first clause, becauseFoo.hashCode
overrides fromFoo
the methodObject.hashCode
.For the interface declaration, consider that while an interface does not have
Object
as a supertype, an interface does havepublic
abstract
members that correspond to thepublic
members ofObject
(9.2). If an interface chooses to declare them explicitly (that is, to declare members that are override-equivalent topublic
methods ofObject
), then the interface is deemed to override them, and use of@Override
is allowed.However, consider an interface that attempts to use
@Override
on aclone
method: (finalize
could also be used in this example)interface Quux { @Override Object clone(); }
Because
Object.clone
is notpublic
, there is no member calledclone
implicitly declared inQuux
. Therefore, the explicit declaration ofclone
inQuux
is not deemed to "implement" any other method, and it is erroneous to use@Override
. (The fact thatQuux.clone
ispublic
is not relevant.)In contrast, a class declaration that declares
clone
is simply overridingObject.clone
, so is able to use@Override
:class Beep { @Override protected Object clone() {..} }
9.6.4.5 @SuppressWarnings
Java compilers are increasingly capable of issuing helpful "lint-like" warnings. To encourage the use of such warnings, there should be some way to disable a warning in a part of the program when the programmer knows that the warning is inappropriate.
The annotation type interface SuppressWarnings
supports programmer control over warnings otherwise issued by a Java compiler. It defines a single element that is an array of String
.
If a declaration is annotated with @SuppressWarnings(value = {S1, ..., Sk})
, then a Java compiler must suppress (that is, not report) any warning specified by one of S1 ... Sk if that warning would have been generated as a result of the annotated declaration or any of its parts.
The Java programming language defines four kinds of warnings that can be specified by @SuppressWarnings
:
Unchecked warnings (4.8, 5.1.6, 5.1.9, 8.4.1, 8.4.8.3, 15.12.4.2, 15.13.2, 15.27.3) are specified by the string "
unchecked
".Deprecation warnings (9.6.4.6) are specified by the string "
deprecation
".Removal warnings (9.6.4.6) are specified by the string "
removal
".Preview warnings (1.5) are specified by the string "
preview
".
Any other string specifies a non-standard warning. A Java compiler must ignore any such string that it does not recognize.
Compiler vendors are encouraged to document the strings they support for
@SuppressWarnings
, and to cooperate to ensure that the same strings are recognized across multiple compilers.
9.6.4.6 @Deprecated
Programmers are sometimes discouraged from using certain program elements (modules, types classes, interfaces, fields, methods, and constructors) because they are dangerous or because a better alternative exists. The annotation type interface Deprecated
allows a compiler to warn about uses of these program elements.
A deprecated program element is a module, type class, interface, field, method, or constructor whose declaration is annotated with @Deprecated
. The manner in which a program element is deprecated depends on the value of the forRemoval
element of the annotation:
If
forRemoval=false
(the default), then the program element is ordinarily deprecated.An ordinarily deprecated program element is not intended to be removed in a future release, but programmers should nevertheless migrate away from using it.
If
forRemoval=true
, then the program element is terminally deprecated.A terminally deprecated program element is intended to be removed in a future release. Programmers should stop using it or risk source and binary incompatibilities (13.2) when upgrading to a newer release.
A Java compiler must produce a deprecation warning when an ordinarily deprecated program element is used (overridden, invoked, or referenced by name) in the declaration of a program element (whether explicitly or implicitly declared), unless:
The use is within a declaration that is itself deprecated, either ordinarily or terminally; or
The use is within a declaration that is annotated to suppress deprecation warnings (9.6.4.5); or
The declaration where the use appears and the declaration of the ordinarily deprecated program element are both within the same outermost class; or
The use is within an
import
declaration that imports the ordinarily deprecated type or member; orThe use is within an
exports
oropens
directive (7.7.2).
A Java compiler must produce a removal warning when a terminally deprecated program element is used (overridden, invoked, or referenced by name) in the declaration of a program element (whether explicitly or implicitly declared), unless:
The use is within a declaration that is annotated to suppress removal warnings (9.6.4.5); or
The declaration where the use appears and the declaration of the terminally deprecated program element are both within the same outermost class; or
The use is within an
import
declaration that imports the terminally deprecatedtypeclass, interface, or member; orThe use is within an
exports
oropens
directive.
Terminal deprecation is sufficiently urgent that the use of a terminally deprecated element will cause a removal warning even if the using element is itself deprecated, since there is no guarantee that both elements will be removed at the same time. To dismiss the warning but continue using the element, the programmer must manually acknowledge the risk via an
@SuppressWarnings
annotation.
No deprecation warning or removal warning is produced when:
a local variable or formal parameter is used (referenced by name), even if the declaration of the local variable or formal parameter is annotated with
@Deprecated
.the name of a package is used (referenced by a qualified type name, or an
import
declaration, or anexports
oropens
directive), even if the declaration of the package is annotated with@Deprecated
.the name of a module is used by a qualified
exports
oropens
directive, even if the declaration of the friend module is annotated with@Deprecated
.
A module declaration that exports or opens a package is usually controlled by the same programmer or team that controls the package's declaration. As such, there is little benefit in warning that the package declaration is annotated with
@Deprecated
when the package is exported or opened by the module declaration. In contrast, a module declaration that exports or opens a package to a friend module is usually not controlled by the same programmer or team that controls the friend module. Simply exporting or opening the package does not make the module declaration rely on the friend module, so there is little value in warning if the friend module is deprecated; the programmer of the module declaration would almost always wish to suppress such a warning.
The only implicit declaration that can cause a deprecation warning or removal warning is a container annotation (9.7.5). Namely, if T is a repeatable annotation
typeinterface and TC is its containing annotationtypeinterface, and TC is deprecated, then repeating the@T
annotation will cause a warning. The warning is due to the implicit@TC
container annotation. It is strongly discouraged to deprecate a containing annotationtypeinterface without deprecating the corresponding repeatable annotationtypeinterface.
9.6.4.7 @SafeVarargs
A variable arity parameter with a non-reifiable element type (4.7) can cause heap pollution (4.12.2) and give rise to compile-time unchecked warnings (5.1.9). Such warnings are uninformative if the body of the variable arity method is well-behaved with respect to the variable arity parameter.
The annotation type interface SafeVarargs
, when used to annotate a method or constructor declaration, makes a programmer assertion that prevents a Java compiler from reporting unchecked warnings for the declaration or invocation of a variable arity method or constructor where the compiler would otherwise do so due to the variable arity parameter having a non-reifiable element type.
The annotation
@SafeVarargs
has non-local effects because it suppresses unchecked warnings at method invocation expressions, in addition to an unchecked warning pertaining to the declaration of the variable arity method itself (8.4.1). In contrast, the annotation@SuppressWarnings("unchecked")
has local effects because it only suppresses unchecked warnings pertaining to the declaration of a method.
The canonical target for
@SafeVarargs
is a method likejava.util.Collections.addAll
, whose declaration starts with:public static <T> boolean addAll(Collection<? super T> c, T... elements)
The variable arity parameter has declared type
T[]
, which is non-reifiable. However, the method fundamentally just reads from the input array and adds the elements to a collection, both of which are safe operations with respect to the array. Therefore, any compile-time unchecked warnings at method invocation expressions forjava.util.Collections.addAll
are arguably spurious and uninformative. Applying@SafeVarargs
to the method declaration prevents generation of these unchecked warnings at the method invocation expressions.
It is a compile-time error if a fixed arity method or constructor declaration is annotated with the annotation @SafeVarargs
.
It is a compile-time error if a variable arity method declaration that is neither static
nor final
nor private
is annotated with the annotation @SafeVarargs
.
Since
@SafeVarargs
is only applicable tostatic
methods,final
and/orprivate
instance methods, and constructors, the annotation is not usable where method overriding occurs. Annotation inheritance only works for annotations on classes (not on methods, interfaces, or constructors), so an@SafeVarargs
-style annotation cannot be passed through instance methods in classes or through interfaces.
9.6.4.8 @Repeatable
The annotation type interface java.lang.annotation.Repeatable
is used on the declaration of a repeatable annotation type interface to indicate its containing annotation type interface (9.6.3).
Note that an
@Repeatable
meta-annotation on the declaration of T, indicating TC, is not sufficient to make TC the containing annotationtypeinterface of T. There are numerous well-formedness rules for TC to be considered the containing annotationtypeinterface of T.
9.6.4.9 @FunctionalInterface
The annotation type interface FunctionalInterface
is used to indicate that an interface is meant to be a functional interface (9.8). It facilitates early detection of inappropriate method declarations appearing in or inherited by an interface that is meant to be functional.
It is a compile-time error if an interface declaration is annotated with @FunctionalInterface
but is not, in fact, a functional interface.
Because some interfaces are functional incidentally, it is not necessary or desirable that all declarations of functional interfaces be annotated with @FunctionalInterface
.
9.7 Annotations
An annotation is a marker which associates information with a program construct, but has no effect at run time. An annotation denotes a specific invocation instance of an annotation type interface (9.6) and usually provides values for the elements of that type interface.
There are three kinds of annotations. The first kind is the most general, while the other kinds are merely shorthands for the first kind.
- Annotation:
- NormalAnnotation
- MarkerAnnotation
- SingleElementAnnotation
Normal annotations are described in 9.7.1, marker annotations in 9.7.2, and single element annotations in 9.7.3. Annotations may appear at various syntactic locations in a program, as described in 9.7.4. The number of annotations of the same type interface that may appear at a location is determined by their type the interface declaration, as described in 9.7.5.
9.7.1 Normal Annotations
A normal annotation specifies the name of an annotation type interface and optionally a list of comma-separated element-value pairs. Each pair contains an element value that is associated with an element of the annotation type interface (9.6.1).
- NormalAnnotation:
@
TypeName(
[ElementValuePairList])
- ElementValuePairList:
- ElementValuePair {
,
ElementValuePair} - ElementValuePair:
- Identifier
=
ElementValue - ElementValue:
- ConditionalExpression
- ElementValueArrayInitializer
- Annotation
- ElementValueArrayInitializer:
{
[ElementValueList] [,
]}
- ElementValueList:
- ElementValue {
,
ElementValue}
Note that the at-sign (
@
) is a token unto itself (3.11). It is possible to put whitespace between it and the TypeName, but this is discouraged as a matter of style.
The TypeName specifies the annotation type interface corresponding to the annotation. The annotation is said to be "of" that type interface.
The TypeName must name an accessible annotation type interface (6.6), or a compile-time error occurs.
The Identifier in an element-value pair must be the simple name of one of the elements (that is, methods) of the annotation type interface, or a compile-time error occurs.
The return type of this method defines the element type of the element-value pair.
If the element type is an array type, then it is not required to use curly braces to specify the element value of the element-value pair. If the element value is not an ElementValueArrayInitializer, then an array value whose sole element is the element value is associated with the element. If the element value is an ElementValueArrayInitializer, then the array value represented by the ElementValueArrayInitializer is associated with the element.
It is a compile-time error if the element type is not commensurate with the element value. An element type T is commensurate with an element value V if and only if one of the following is true:
T is an array type E
[]
, and either:If V is a ConditionalExpression or an Annotation, then V is commensurate with E; or
If V is an ElementValueArrayInitializer, then each element value that V contains is commensurate with E.
An ElementValueArrayInitializer is similar to a normal array initializer ([10.6]), except that an ElementValueArrayInitializer may syntactically contain annotations as well as expressions and nested initializers. However, nested initializers are not semantically legal in an ElementValueArrayInitializer because they are never commensurate with array-typed elements in annotation
typeinterface declarations (nested array types not permitted).
T is not an array type, and the type of V is assignment compatible ([5.2]) with T, and:
Note that if T is not an array type or an annotation interface type, the element value must be a ConditionalExpression ([15.25]). The use of ConditionalExpression rather than a more general production like Expression is a syntactic trick to prevent assignment expressions as element values. Since an assignment expression is not a constant expression, it cannot be a commensurate element value for a primitive or
String
-typed element.
Formally, it is invalid to speak of an ElementValue as FP-strict (15.4) because it might be an annotation or a class literal. Still, we can speak informally of ElementValue as FP-strict when it is either a constant expression or an array of constant expressions or an annotation whose element values are (recursively) found to be constant expressions; after all, every constant expression is FP-strict.
A normal annotation must contain an element-value pair for every element of the corresponding annotation type interface, except for those elements with default values, or a compile-time error occurs.
A normal annotation may, but is not required to, contain element-value pairs for elements with default values.
It is customary, though not required, that element-value pairs in an annotation are presented in the same order as the corresponding elements in the annotation
typedeclaration.
An annotation on an annotation type declaration is known as a meta-annotation.
An annotation of type T interface A may appear as a meta-annotation on the declaration of type T the interface A itself. More generally, circularities in the transitive closure of the "annotates" relation are permitted.
For example, it is legal to annotate the declaration of an annotation
typeinterface S with a meta-annotation oftypeinterface T, and to annotate T's own declaration with a meta-annotation oftypeinterface S. The pre-defined annotationtypesinterfaces contain several such circularities.
Example 9.7.1-1. Normal Annotations
Here is an example of a normal annotation using the annotation type interface from 9.6.1:
@RequestForEnhancement(
id = 2868724,
synopsis = "Provide time-travel functionality",
engineer = "Mr. Peabody",
date = "4/1/2004"
)
public static void travelThroughTime(Date destination) { ... }
Here is an example of a normal annotation that takes advantage of default values, using the annotation type interface from 9.6.2:
@RequestForEnhancement(
id = 4561414,
synopsis = "Balance the federal budget"
)
public static void balanceFederalBudget() {
throw new UnsupportedOperationException("Not implemented");
}
9.7.2 Marker Annotations
A marker annotation is a shorthand designed for use with marker annotation types interfaces (9.6.1).
- MarkerAnnotation:
@
TypeName
It is shorthand for the normal annotation:
@*TypeName*()
It is legal to use marker annotations for annotation types interfaces with elements, so long as all the elements have default values (9.6.2).
Example 9.7.2-1. Marker Annotations
Here is an example using the Preliminary
marker annotation type interface from 9.6.1:
@Preliminary public class TimeTravel { ... }
9.7.3 Single-Element Annotations
A single-element annotation, is a shorthand designed for use with single-element annotation types interfaces (9.6.1).
- SingleElementAnnotation:
@
TypeName(
ElementValue)
It is shorthand for the normal annotation:
@*TypeName*(value = *ElementValue*)
It is legal to use single-element annotations for annotation types interfaces with multiple elements, so long as one element is named value
and all other elements have default values (9.6.2).
Example 9.7.3-1. Single-Element Annotations
The following annotations all use the single-element annotation types interfaces from 9.6.1.
Here is an example of a single-element annotation:
@Copyright("2002 Yoyodyne Propulsion Systems, Inc.")
public class OscillationOverthruster { ... }
Here is an example of an array-valued single-element annotation:
@Endorsers({"Children", "Unscrupulous dentists"})
public class Lollipop { ... }
Here is an example of a single-element array-valued single-element annotation: (note that the curly braces are omitted)
@Endorsers("Epicurus")
public class Pleasure { ... }
Here is an example of a single-element annotation with a Class
-typed element whose value is constrained by a bounded wildcard.
class GorgeousFormatter implements Formatter { ... }
@PrettyPrinter(GorgeousFormatter.class)
public class Petunia { ... }
// Illegal; String is not a subtype of Formatter
@PrettyPrinter(String.class)
public class Begonia { ... }
Here is an example with of a single-element annotation that contains a normal annotation:
@Author(@Name(first = "Joe", last = "Hacker"))
public class BitTwiddle { ... }
Here is an example of a single-element annotation that uses an enum type class defined inside the annotation type declaration:
@Quality(Quality.Level.GOOD)
public class Karma { ... }
9.7.4 Where Annotations May Appear
A declaration annotation is an annotation that applies to a declaration, and whose own type annotation interface is applicable in the declaration context (9.6.4.1) represented by that declaration; or an annotation that applies to a class, interface, enum, annotation type, or type parameter declaration, and whose own type annotation interface is applicable in type contexts (4.11).
A type annotation is an annotation that applies to a type (or any part of a type), and whose own type annotation interface is applicable in type contexts.
For example, given the field declaration:
@Foo int f;
@Foo
is a declaration annotation onf
ifFoo
is meta-annotated by@Target(ElementType.FIELD)
, and a type annotation onint
ifFoo
is meta-annotated by@Target(ElementType.TYPE_USE)
. It is possible for@Foo
to be both a declaration annotation and a type annotation simultaneously.Type annotations can apply to an array type or any component type thereof (10.1). For example, assuming that
A
,B
, andC
are annotationtypesinterfaces meta-annotated with@Target(ElementType.TYPE_USE)
, then given the field declaration:@C int @A [] @B [] f;
@A
applies to the array typeint[][]
,@B
applies to its component typeint[]
, and@C
applies to the element typeint
. For more examples, see 10.2.An important property of this syntax is that, in two declarations that differ only in the number of array levels, the annotations to the left of the type refer to the same type. For example,
@C
applies to the typeint
in all of the following declarations:@C int f; @C int[] f; @C int[][] f;
It is customary, though not required, to write declaration annotations before all other modifiers, and type annotations immediately before the type to which they apply.
It is possible for an annotation to appear at a syntactic location in a program where it could plausibly apply to a declaration, or a type, or both. This can happen in any of the five declaration contexts where modifiers immediately precede the type of the declared entity:
Method declarations (including elements of annotation
typesinterfaces)Constructor declarations
Field declarations (including enum constants)
Formal and exception parameter declarations
Local variable declarations (including loop variables of
for
statements and resource variables oftry
-with-resources statements)
The grammar of the Java programming language unambiguously treats annotations at these locations as modifiers for a declaration (8.3), but that is purely a syntactic matter. Whether an annotation applies to the declaration or to the type of the declared entity - and thus, whether the annotation is a declaration annotation or a type annotation - depends on the applicability of the annotation's type interface:
If the annotation's
typeinterface is applicable in the declaration context corresponding to the declaration, and not in type contexts, then the annotation is deemed to apply only to the declaration.If the annotation's
typeinterface is applicable in type contexts, and not in the declaration context corresponding to the declaration, then the annotation is deemed to apply only to the type which is closest to the annotation.If the annotation's
typeinterface is applicable in the declaration context corresponding to the declaration and in type contexts, then the annotation is deemed to apply to both the declaration and the type which is closest to the annotation.
In the second and third cases above, the type which is closest to the annotation is determined as follows:
If the annotation appears before a
void
method declaration or a local variable declaration that usesvar
(14.4, 14.14.2, 14.20.3), then there is no closest type. If the annotation'stypeinterface is deemed to apply only to the type which is closest to the annotation, a compile-time error occurs.If the annotation appears before a constructor declaration, then the closest type is the type of the newly constructed object. The type of the newly constructed object is the fully qualified name of the type immediately enclosing the constructor declaration. Within that fully qualified name, the annotation applies to the simple type name indicated by the constructor declaration.
In all other cases, the closest type is the type written in source code for the declared entity; if that type is an array type, then the element type is deemed to be closest to the annotation.
For example, in the field declaration
@Foo public static String f;
, the type which is closest to@Foo
isString
. (If the type of the field declaration had been written asjava.lang.String
, thenjava.lang.String
would be the type closest to@Foo
, and later rules would prohibit a type annotation from applying to the package namejava
.) In the generic method declaration@Foo <T> int[] m() {...}
, the type written for the declared entity isint[]
, so@Foo
applies to the element typeint
.Local variable declarations which do not use
var
are similar to formal parameter declarations of lambda expressions, in that both allow declaration annotations and type annotations in source code, but only the type annotations can be stored in theclass
file.
It is a compile-time error if an annotation of type T interface A is syntactically a modifier for:
a module declaration, but
TA is not applicable to module declarations.a package declaration, but
TA is not applicable to package declarations.a class
,or interface, or enumdeclaration, butTA is not applicable to type declarations or type contexts; or in the case of an annotationtypedeclaration,but TA is not applicable to annotation type declarations or type declarations or type contexts.a method declaration (including an element of an annotation
typeinterface), butTA is not applicable to method declarations or type contexts.a constructor declaration, but
TA is not applicable to constructor declarations or type contexts.a type parameter declaration of a generic class, interface, method, or constructor, but
TA is not applicable to type parameter declarations or type contexts.a field declaration
(includingor an enum constant), butTA is not applicable to field declarations or type contexts.a formal or exception parameter declaration, but
TA is not applicable to either formal and exception parameter declarations or type contexts.a receiver parameter, but
TA is not applicable to type contexts.a local variable declaration (including a loop variable of a
for
statement or a resource variable of atry
-with-resources statement), butTA is not applicable to local variable declarations or type contexts.
Five of these nine clauses mention "... or type contexts" because they characterize the five syntactic locations where an annotation could plausibly apply either to a declaration or to the type of a declared entity. Furthermore, two of the nine clauses - for class
,and interface, enum, and annotation typedeclarations, and for type parameter declarations - mention "... or type contexts" because it may be convenient to apply an annotation whosetypeinterface is meta-annotated with@Target(ElementType.TYPE_USE)
(thus, applicable in type contexts) to atypeclass, interface, or type parameter declaration.
A type annotation is admissible if both of the following are true:
The simple name to which the annotation is closest is classified as a TypeName, not a PackageName.
If the simple name to which the annotation is closest is followed by "
.
" and another TypeName - that is, the annotation appears as@Foo T.U
- thenU
denotes an inner class ofT
.
The intuition behind the second clause is that if
Outer.this
is legal in a nested class enclosed byOuter
, thenOuter
may be annotated because it represents the type of some object at run time. On the other hand, ifOuter.this
is not legal - because the class where it appears has no enclosing instance ofOuter
at run time - thenOuter
may not be annotated because it is logically just a name, akin to components of a package name in a fully qualified type name.
For example, in the following program, it is not possible to write
A.this
in the body ofB
, asB
has no lexically enclosing instances (8.5.1). Therefore, it is not possible to apply@Foo
toA
in the typeA.B
, becauseA
is logically just a name, not a type.@Target(ElementType.TYPE_USE) @interface Foo {} class A { static class B {} } @Foo A.B x; // Illegal
On the other hand, in the following program, it is possible to write
C.this
in the body ofD
. Therefore, it is possible to apply@Foo
toC
in the typeC.D
, becauseC
represents the type of some object at run time.@Target(ElementType.TYPE_USE) @interface Foo {} class Test { static class C { class D {} } @Foo C.D x; // Legal }
It is a compile-time error if an annotation of type T interface A applies to the outermost level of a type in a type context, and T A is not applicable in type contexts or the declaration context (if any) which occupies the same syntactic location.
It is a compile-time error if an annotation of type T interface A applies to a part of a type (that is, not the outermost level) in a type context, and T A is not applicable in type contexts.
It is a compile-time error if an annotation of type T interface A applies to a type (or any part of a type) in a type context, and T A is applicable in type contexts, and but the annotation is not admissible.
For example, assume an annotation
typeinterfaceTA
which is meta-annotated with just@Target(ElementType.TYPE_USE)
. The terms@TA java.lang.Object
andjava.@TA lang.Object
are illegal because the simple name to which@TA
is closest is classified as a package name. On the other hand,java.lang.@TA Object
is legal.
Note that the illegal terms are illegal "everywhere". The ban on annotating package names applies broadly: to locations which are solely type contexts, such as
class ... extends @TA java.lang.Object {...}
, and to locations which are both declaration and type contexts, such as@TA java.lang.Object f;
. (There are no locations which are solely declaration contexts where a package name could be annotated, as class, package, and type parameter declarations use only simple names.)
If
TA
is additionally meta-annotated with@Target(ElementType.FIELD)
, then the term@TA java.lang.Object
is legal in locations which are both declaration and type contexts, such as a field declaration@TA java.lang.Object f;
. Here,@TA
is deemed to apply to the declaration off
(and not to the typejava.lang.Object
) becauseTA
is applicable in the field declaration context.
9.7.5 Multiple Annotations of the Same Type Interface
It is a compile-time error if multiple annotations of the same type T interface A appear in a declaration context or type context, unless T A is repeatable (9.6.3) and both T A and the containing annotation type interface of T A are applicable in the declaration context or type context (9.6.4.1).
It is customary, though not required, for multiple annotations of the same
typeinterface to appear contiguously.
If a declaration context or type context has multiple annotations of a repeatable annotation type T interface A, then it is as if the context has no explicitly declared annotations of type T interface A and one implicitly declared annotation of the containing annotation type interface of T A.
The implicitly declared annotation is called the container annotation, and the multiple annotations of type T interface A which appeared in the context are called the base annotations. The elements of the (array-typed) value
element of the container annotation are all the base annotations in the left-to-right order in which they appeared in the context.
It is a compile-time error if, in a declaration context or type context, there are multiple annotations of a repeatable annotation type T interface A and any annotations of the containing annotation type interface of T A.
In other words, it is not possible to repeat annotations where an annotation of the same
typeinterface as their container also appears. This prohibits obtuse code like:
@Foo(0) @Foo(1) @FooContainer({@Foo(2)}) class A {}
If this code was legal, then multiple levels of containment would be needed: first the annotations of
typeinterfaceFoo
would be contained by an implicitly declared container annotation oftypeinterfaceFooContainer
, then that annotation and the explicitly declared annotation oftypeinterfaceFooContainer
would be contained in yet another implicitly declared annotation. This complexity is undesirable in the judgment of the designers of the Java programming language. Another approach, treating the annotations oftypeinterfaceFoo
as if they had occurred alongside@Foo(2)
in the explicit@FooContainer
annotation, is undesirable because it could change how reflective programs interpret the@FooContainer
annotation.
It is a compile-time error if, in a declaration context or type context, there is one annotation of a repeatable annotation type T interface A and multiple annotations of the containing annotation type interface of T A.
This rule is designed to allow the following code:
@Foo(1) @FooContainer({@Foo(2)}) class A {}
With only one annotation of the repeatable annotation
typeinterfaceFoo
, no container annotation is implicitly declared, even ifFooContainer
is the containing annotationtypeinterface ofFoo
. However, repeating the annotation oftypeinterfaceFooContainer
, as in:
@Foo(1) @FooContainer({@Foo(2)}) @FooContainer({@Foo(3)}) class A {}
is prohibited, even if
FooContainer
is repeatable with a containing annotationtypeinterface of its own. It is obtuse to repeat annotations which are themselves containers when an annotation of the underlying repeatabletypeinterface is present.
Chapter 12: Execution
12.2 Loading of Classes and Interfaces
Loading refers to the process of finding the binary form of a class or interface type with a particular name, perhaps by computing it on the fly, but more typically by retrieving a binary representation previously computed from source code by a Java compiler, and constructing, from that binary form, a Class
object to represent the class or interface.
The precise semantics of loading are given in Chapter 5 of The Java Virtual Machine Specification, Java SE 15 Edition. Here we present an overview of the process from the viewpoint of the Java programming language.
The binary format of a class or interface is normally the class
file format described in The Java Virtual Machine Specification, Java SE 15 Edition cited above, but other formats are possible, provided they meet the requirements specified in 13.1. The method defineClass
of class ClassLoader
may be used to construct Class
objects from binary representations in the class
file format.
Well-behaved class loaders maintain these properties:
Given the same name, a good class loader should always return the same class object.
If a class loader L1 delegates loading of a class C to another loader L2, then for any
type Tclass or interface D thatoccurs asis named by the direct superclass type or a direct superinterface type of C, orasby the type of a field in C, orasby the type of a formal parameter of a method or constructor in C, orasby a return type of a method in C, L1 and L2 should return the sameClass
object.
A malicious class loader could violate these properties. However, it could not undermine the security of the type system, because the Java Virtual Machine guards against this.
For further discussion of these issues, see The Java Virtual Machine Specification, Java SE 15 Edition and the paper Dynamic Class Loading in the Java Virtual Machine, by Sheng Liang and Gilad Bracha, in Proceedings of OOPSLA '98, published as ACM SIGPLAN Notices, Volume 33, Number 10, October 1998, pages 36-44. A basic principle of the design of the Java programming language is that the run-time type system cannot be subverted by code written in the Java programming language, not even by implementations of such otherwise sensitive system classes as
ClassLoader
andSecurityManager
.
12.3 Linking of Classes and Interfaces
Linking is the process of taking a binary form of a class or interface type and combining it into the run-time state of the Java Virtual Machine, so that it can be executed. A class or interface type is always loaded before it is linked.
Three different activities are involved in linking: verification, preparation, and resolution of symbolic references.
The precise semantics of linking are given in Chapter 5 of The Java Virtual Machine Specification, Java SE 15 Edition. Here we present an overview of the process from the viewpoint of the Java programming language.
This specification allows an implementation flexibility as to when linking activities (and, because of recursion, loading) take place, provided that the semantics of the Java programming language are respected, that a class or interface is completely verified and prepared before it is initialized, and that errors detected during linkage are thrown at a point in the program where some action is taken by the program that might require linkage to the class or interface involved in the error.
For example, an implementation may choose to resolve each symbolic reference in a class or interface individually, only when it is used (lazy or late resolution), or to resolve them all at once while the class is being verified (static resolution). This means that the resolution process may continue, in some implementations, after a class or interface has been initialized.
Because linking involves the allocation of new data structures, it may fail with an OutOfMemoryError
.
12.3.3 Resolution of Symbolic References
The binary representation of a class or interface references other classes and interfaces and their fields, methods, and constructors symbolically, using the binary names (13.1) of the other classes and interfaces (13.1). For fields and methods, these symbolic references include the name of the class or interface type of which the field or method is a member, as well as the name of the field or method itself, together with appropriate type information.
Before a symbolic reference can be used it must undergo resolution, wherein a symbolic reference is checked to be correct and, typically, replaced with a direct reference that can be more efficiently processed if the reference is used repeatedly.
If an error occurs during resolution, then an error will be thrown. Most typically, this will be an instance of one of the following subclasses of the class IncompatibleClassChangeError
, but it may also be an instance of some other subclass of IncompatibleClassChangeError
or even an instance of the class IncompatibleClassChangeError
itself. This error may be thrown at any point in the program that uses a symbolic reference to the type, directly or indirectly:
Could change this to "class or interface", but symbolic references aren't just references to classes and interfaces.
...
12.5 Creation of New Class Instances
...
Whenever a new class instance is created, memory space is allocated for it with room for all the instance variables declared in the class type and all the instance variables declared in each superclass of the class type, including all the instance variables that may be hidden (8.3).
...
Chapter 13: Binary Compatibility
13.1 The Form of a Binary
Programs must be compiled either into the class
file format specified by The Java Virtual Machine Specification, Java SE 14 Edition, or into a representation that can be mapped into that format by a class loader written in the Java programming language.
A class
file corresponding to a class or interface declaration must have certain properties. A number of these properties are specifically chosen to support source code transformations that preserve binary compatibility. The required properties are:
The class or interface must be named by its binary name, which must meet the following constraints:
The binary name of a top level
typeclass or interface (7.6) is its canonical name (6.7).The binary name of a member
typeclass or interface (8.5, 9.5) consists of the binary name of its immediately enclosingtypeclass or interface, followed by$
, followed by the simple name of the member.The binary name of a local class (14.3) consists of the binary name of its immediately enclosing
typeclass or interface, followed by$
, followed by a non-empty sequence of digits, followed by the simple name of the local class.The binary name of an anonymous class (15.9.5) consists of the binary name of its immediately enclosing
typeclass or interface, followed by$
, followed by a non-empty sequence of digits.The binary name of a type variable declared by a generic class or interface (8.1.2, 9.1.2) is the binary name of its immediately enclosing
typeclass or interface, followed by$
, followed by the simple name of the type variable.The binary name of a type variable declared by a generic method (8.4.4) is the binary name of the
typeclass or interface declaring the method, followed by$
, followed by the descriptor of the method (JVMS §4.3.3), followed by$
, followed by the simple name of the type variable.The binary name of a type variable declared by a generic constructor (8.8.4) is the binary name of the
typeclass declaring the constructor, followed by$
, followed by the descriptor of the constructor (JVMS §4.3.3), followed by$
, followed by the simple name of the type variable.
It's unclear why a type variable should have a binary name at all...
A reference to another class or interface
typemust be symbolic, using the binary name of thetypeclass or interface.A reference to a field that is a constant variable (4.12.4) must be resolved at compile time to the value V denoted by the constant variable's initializer.
If such a field is
static
, then no reference to the field should be present in the code in a binary file, including the class or interface which declared the field. Such a field must always appear to have been initialized (12.4.2); the default initial value for the field (if different than V) must never be observed.If such a field is non-
static
, then no reference to the field should be present in the code in a binary file, except in the class containing the field. (It will be a class rather than an interface, since an interface has onlystatic
fields.) The class should have code to set the field's value to V during instance creation (12.5).Given a legal expression denoting a field access in a class C, referencing a field named f that is not a constant variable and is declared in a (possibly distinct) class or interface D, we define the qualifying
typeclass or interface of the field reference as follows:If the expression is referenced by a simple name, then if f is a member of the current class or interface, C, then let
TQ be C. Otherwise, letTQ be the innermost lexically enclosingtypeclass or interface declaration of which f is a member. In either case,TQ is the qualifyingtypeclass or interface of the reference.If the reference is of the form TypeName
.
f, where TypeName denotes a class or interface, then the class or interface denoted by TypeName is the qualifyingtypeclass or interface of the reference.If the expression is of the form ExpressionName
.
f or Primary.
f, then:If the compile-time type of ExpressionName or Primary is an intersection type V1
&
...&
Vn (4.9), then the qualifyingtypeclass or interface of the reference is the erasure (4.6) of V1.Otherwise, the erasure of the compile-time type of ExpressionName or Primary is the qualifying
typeclass or interface of the reference.
If the expression is of the form
super.
f, then the superclass of C is the qualifyingtypeclass or interface of the reference.If the expression is of the form TypeName
.super.
f, then the superclass of the class denoted by TypeName is the qualifyingtypeclass or interface of the reference.
The reference to f must be compiled into a symbolic reference to the
erasure (4.6) of thequalifyingtypeclass or interface of the reference, plus the simple name of the field, f. The reference must also include a symbolic reference to the erasure of the declared type of the field so that the verifier can check that the type is as expected.Given a method invocation expression or a method reference expression in a class or interface C, referencing a method named m declared (or implicitly declared (9.2)) in a (possibly distinct) class or interface D, we define the qualifying
typeclass or interface of the method invocation as follows:If D is
Object
then the qualifyingtypeclass or interface of the expression isObject
.Otherwise:
If the method is referenced by a simple name, then if m is a member of the current class or interface C, let
TQ be C; otherwise, letTQ be the innermost lexically enclosingtypeclass or interface declaration of which m is a member. In either case,TQ is the qualifyingtypeclass or interface of the method invocation.If the expression is of the form TypeName
.
m or ReferenceType::
m, then thetypeclass or interface denoted by TypeName, or the erasure (4.6) of ReferenceType, is the qualifyingtypeclass or interface of the method invocation.If the expression is of the form ExpressionName
.
m or Primary.
m or ExpressionName::
m or Primary::
m, then:If the compile-time type of ExpressionName or Primary is an intersection type V1
&
...&
Vn (4.9), then the qualifyingtypeclass or interface of the method invocation is the erasure of V1.Otherwise, the erasure of the compile-time type of ExpressionName or Primary is the qualifying
typeclass or interface of the method invocation.
If the expression is of the form
super.
m orsuper::
m, then the superclass of C is the qualifyingtypeclass or interface of the method invocation.If the expression is of the form TypeName
.super.
m or TypeName.super::
m, then if TypeName denotes a class X, the superclass of X is the qualifyingtypeclass or interface of the method invocation; if TypeName denotes an interface X, X is the qualifyingtypeclass or interface of the method invocation.
A reference to a method must be resolved at compile time to a symbolic reference to the
erasure (4.6) of thequalifyingtypeclass or interface of the invocation, plus the erasure of the declared signature (8.4.2) of the method. The signature of a method must include all of the following as determined by 15.12.3:The simple name of the method
The number of parameters to the method
A symbolic reference to the type of each parameter
A reference to a method must also include either a symbolic reference to the erasure of the return type of the denoted method or an indication that the denoted method is declared
void
and does not return a value.Given a class instance creation expression (15.9) or an explicit constructor invocation statement (8.8.7.1) or a method reference expression of the form ClassType
::
new
(15.13) in a class or interface C referencing a constructor m declared in a (possibly distinct) class or interface D, we define the qualifyingtypeclass of the constructor invocation as follows:If the expression is of the form
new
D(...)
or ExpressionName.new
D(...)
or Primary.new
D(...)
or D::
new
, then the qualifyingtypeclass of the invocation is D.If the expression is of the form
new
D(...){...}
or ExpressionName.new
D(...){...}
or Primary.new
D(...){...}
, then the qualifyingtypeclass of the expression is thecompile-time type ofanonymous class declared by the expression.If the expression is of the form
super(...)
or ExpressionName.super(...)
or Primary.super(...)
, then the qualifyingtypeclass of the expression is the direct superclass of C.If the expression is of the form
this(...)
, then the qualifyingtypeclass of the expression is C.
A reference to a constructor must be resolved at compile time to a symbolic reference to the
erasure (4.6) of thequalifyingtypeclass of the invocation, plus the declared signature of the constructor (8.8.2). The signature of a constructor must include both:The number of parameters of the constructor
A symbolic reference to the type of each formal parameter
A binary representation for a class or interface must also contain all of the following:
If it is a class and is not
Object
, then a symbolic reference to theerasure of thedirect superclass of this class.A symbolic reference to
the erasure ofeach direct superinterface, if any.A specification of each field declared in the class or interface, given as the simple name of the field and a symbolic reference to the erasure of the type of the field.
If it is a class, then the erased signature of each constructor, as described above.
For each method declared in the class or interface (excluding, for an interface, its implicitly declared methods (9.2)), its erased signature and return type, as described above.
The code needed to implement the class or interface:
For an interface, code for the field initializers and the implementation of each method with a block body (9.4.3).
For a class, code for the field initializers, the instance and static initializers, the implementation of each method with a block body (8.4.7), and the implementation of each constructor.
Every
typeclass or interface must contain sufficient information to recover its canonical name (6.7).Every member
typeclass or interface must have sufficient information to recover its source-level access modifier.Every nested class
and nestedor interface must have a symbolic reference to its immediately enclosingtypeclass or interface (8.1.3).Every class or interface must contain symbolic references to all of its member
typesclasses and interfaces (8.5, 9.5), and to alllocal and anonymous classes that appear in its methods, constructors, static initializers, instance initializers, and field initializersother nested classes and interfaces declared within its body.Every interface must contain symbolic references to all of its member types (9.5), and to all local and anonymous classes that appear in its default methods and field initializers.A construct emitted by a Java compiler must be marked as synthetic if it does not correspond to a construct declared explicitly or implicitly in source code, unless the emitted construct is a class initialization method (JVMS §2.9).
A construct emitted by a Java compiler must be marked as mandated if it corresponds to a formal parameter declared implicitly in source code (8.8.1, 8.8.9, 8.9.3, 15.9.5.1).
The following formal parameters are declared implicitly in source code:
The first formal parameter of a constructor of a non-
private
inner member class (8.8.1, 8.8.9).The first formal parameter of an anonymous constructor of an anonymous class whose superclass is
inner or localan inner class (not in a static context) (15.9.5.1).The formal parameter
name
of thevalueOf
method which is implicitly declared in an enumtypeclass (8.9.3).
For reference, the following constructs are declared implicitly in source code, but are not marked as mandated because only formal parameters can be so marked in a
class
file (JVMS §4.7.24):
A class
file corresponding to a module declaration must have the properties of a class
file for a class whose binary name is module-info
and which has no superclass, no superinterfaces, no fields, and no methods. In addition, the binary representation of the module must contain all of the following:
A specification of the name of the module, given as a symbolic reference to the name indicated after
module
. Also, the specification must include whether the module is normal or open (7.7).A specification of each dependence denoted by a
requires
directive, given as a symbolic reference to the name of the module indicated by the directive (7.7.1). Also, the specification must include whether the dependence istransitive
and whether the dependence isstatic
.A specification of each package denoted by an
exports
oropens
directive, given as a symbolic reference to the name of the package indicated by the directive (7.7.2). Also, if the directive was qualified, the specification must give symbolic references to the names of the modules indicated by the directive'sto
clause.A specification of each service denoted by a
uses
directive, given as a symbolic reference to the name of thetypeclass or interface indicated by the directive (7.7.3).A specification of the service providers denoted by a
provides
directive, given as symbolic references to the names of thetypesclasses and interfaces indicated by the directive'swith
clause (7.7.4). Also, the specification must give a symbolic reference to the name of thetypeclass or interface indicated as the service by the directive.
The following sections discuss changes that may be made to class and interface type declarations without breaking compatibility with pre-existing binaries. Under the translation requirements given above, the Java Virtual Machine and its class
file format support these changes. Any other valid binary format, such as a compressed or encrypted representation that is mapped back into class
files by a class loader under the above requirements, will necessarily support these changes as well.
13.3 Evolution of Packages and Modules
A new top level class or interface type may be added to a package without breaking compatibility with pre-existing binaries, provided the new type class or interface does not reuse a name previously given to an unrelated type class or interface. If a new type class or interface reuses a name previously given to an unrelated type class or interface, then a conflict may result, since binaries for both types classes or interfaces could not be loaded by the same class loader.
Changes in top level class and interface types classes and interfaces that are not public
and that are not a superclass or superinterface, respectively, of a public
type class or interface, affect only types classes and interfaces within the package in which they are declared. Such types classes and interfaces may be deleted or otherwise changed, even if incompatibilities are otherwise described here, provided that the affected binaries of that package are updated together.
If a module that was declared to export or open a package is changed to not export or open the package, or to export or open the package to a different set of friends, then an IllegalAccessError
is thrown if a pre-existing binary is linked that needs but no longer has access to the public
and protected
types classes and interfaces of the package. Such a change is not recommended for modules that have been widely distributed.
If a module was not declared to export or open a given package, then changing the module to export or open the package does not break compatibility with pre-existing binaries. However, changing the module to export the package may prevent the program from starting, since any module that reads the module may also read some other module that exports a package with the same name.
Adding a requires
directive to a module declaration, or adding the transitive
modifier to a requires
directive, does not break compatibility with pre-existing binaries. However, it may prevent the program from starting, since the module may now read multiple modules that export packages with the same name.
Deleting a requires
directive in a module declaration, or deleting the transitive
modifier from a requires
directive, may break compatibility with any pre-existing binary that relied on the directive or modifier for readability of a given module in the course of referencing types classes and interfaces exported by that module. An IllegalAccessError
may be thrown when such a reference from a pre-existing binary is linked.
Adding or deleting a uses
or provides
directive in a module declaration does not break compatibility with pre-existing binaries.
13.4 Evolution of Classes
13.4.4 Superclasses and Superinterfaces
A ClassCircularityError
is thrown at load time if a class would be a superclass of itself. Changes to the class hierarchy that could result in such a circularity when newly compiled binaries are loaded with pre-existing binaries are not recommended for widely distributed classes.
Changing the direct superclass type or the set of direct superinterfaces superinterface types of a class type will not break compatibility with pre-existing binaries, provided that the total set of superclasses or superinterfaces, respectively, of the class type loses no members.
As one notable example, it is a binary compatible change to replace a raw supertype of a class with a parameterization of the class or interface named by the raw type.
If a change to the direct superclass or the set of direct superinterfaces results in any class or interface no longer being a superclass or superinterface, respectively, then linkage errors may result if pre-existing binaries are loaded with the binary of the modified class. Such changes are not recommended for widely distributed classes.
Example 13.4.4-1. Changing A Superclass
Suppose that the following test program:
class Hyper { char h = 'h'; }
class Super extends Hyper { char s = 's'; }
class Test extends Super {
public static void printH(Hyper h) {
System.out.println(h.h);
}
public static void main(String[] args) {
printH(new Super());
}
}
is compiled and executed, producing the output:
h
Suppose that a new version of class Super
is then compiled:
class Super { char s = 's'; }
This version of class Super
is not a subclass of Hyper
. If we then run the existing binaries of Hyper
and Test
with the new version of Super
, then a VerifyError
is thrown at link time. The verifier objects because the result of new Super()
cannot be passed as an argument in place of a formal parameter of type Hyper
, because Super
is not a subclass of Hyper
.
It is instructive to consider what might happen without the verification step: the program might run and print:
s
This demonstrates that without the verifier, the Java type system could be defeated by linking inconsistent binary files, even though each was produced by a correct Java compiler.
The lesson is that an implementation that lacks a verifier or fails to use it will not maintain type safety and is, therefore, not a valid implementation.
The requirement that alternatives in a multi-
catch
clause (14.20) not be subclasses or superclasses of each other is only a source restriction. Assuming the following client code is legal:try { throwAorB(); } catch(ExceptionA | ExceptionB e) { ... }
where
ExceptionA
andExceptionB
do not have a subclass/superclass relationship when the client is compiled, it is binary compatible with respect to the client forExceptionA
andExceptionB
to have such a relationship when the client is executed.This is analogous to other situations where a class transformation that is binary compatible for a client might not be source compatible for the same client.
13.4.8 Field Declarations
Widely distributed programs should not expose any fields to their clients. Apart from the binary compatibility issues discussed below, this is generally good software engineering practice. Adding a field to a class may break compatibility with pre-existing binaries that are not recompiled.
Assume a reference to a field f with qualifying type T class C. Assume further that f is in fact an instance (respectively static
) field declared in a superclass of T C, S, and that the type of f is X.
If a new field of type X with the same name as f is added to a subclass of S that is a superclass of T C or T C itself, then a linkage error may occur. Such a linkage error will occur only if, in addition to the above, either one of the following is true:
The new field is less accessible than the old one.
The new field is a
static
(respectively instance) field.
In particular, no linkage error will occur in the case where a class could no longer be recompiled because a field access previously referenced a field of a superclass with an incompatible type. The previously compiled class with such a reference will continue to reference the field declared in a superclass.
...
13.4.12 Method and Constructor Declarations
Adding a method or constructor declaration to a class will not break compatibility with any pre-existing binaries, even in the case where a type class could no longer be recompiled because an invocation previously referenced a method or constructor of a superclass with an incompatible type. The previously compiled class with such a reference will continue to reference the method or constructor declared in a superclass.
Assume a reference to a method m with qualifying type T class C. Assume further that m is in fact an instance (respectively static
) method declared in a superclass of T C, S.
If a new method of type X with the same signature and return type as m is added to a subclass of S that is a superclass of T C or T C itself, then a linkage error may occur. Such a linkage error will occur only if, in addition to the above, either one of the following is true:
The new method is less accessible than the old one.
The new method is a
static
(respectively instance) method.
...
13.4.26 Evolution of Enums Enum Classes
Adding or reordering constants in an enum declaration will not break compatibility with pre-existing binaries.
If a pre-existing binary attempts to access an enum constant that no longer exists, the client will fail at run time with a NoSuchFieldError
. Therefore such a change is not recommended for widely distributed enums.
Removing an enum constant will remove the corresponding implicit field declaration, with consequences described in 13.4.8.
In all other respects, the binary compatibility rules for enums enum classes are identical to those for classes normal classes.
13.5 Evolution of Interfaces
13.5.7 Evolution of Annotation Types Interfaces
Annotation types interfaces behave exactly like any other interface. Adding or removing an element from an annotation type interface is analogous to adding or removing a method. There are important considerations governing other changes to annotation types interfaces, such as making an annotation type interface repeatable (9.6.3), but these have no effect on the linkage of binaries by the Java Virtual Machine. Rather, such changes affect the behavior of reflective APIs that manipulate annotations. The documentation of these APIs specifies their behavior when various changes are made to the underlying annotation types interfaces.
Adding or removing annotations has no effect on the correct linkage of the binary representations of programs in the Java programming language.
Chapter 15: Expressions
15.8 Primary Expressions
15.8.2 Class Literals
A class literal is an expression consisting of the name of a class, interface, array type, or primitive type, or the pseudo-type void
, followed by a '.
' and the token class
.
- ClassLiteral:
- TypeName {
[
]
}.
class
- NumericType {
[
]
}.
class
boolean
{[
]
}.
class
void
.
class
The TypeName must denote a class or interface type that is accessible (6.6). It is a compile-time error if the TypeName denotes a class or interface type that is not accessible, or denotes a type variable.
The type of C.class
, where C is the name of a class, interface, or array type (4.3), is Class<
C>
.
The type of p.class
, where p is the name of a primitive type (4.2), is Class<
B>
, where B is the type of an expression of type p after boxing conversion ([5.1.7]).
The type of void.class
(8.4.5) is Class<Void>
.
A class literal evaluates to the Class
object for the named type class, interface, array type, or primitive type (or for void
), as defined by the defining class loader (12.2) of the class of the current instance.
15.8.3 this
The keyword this
may be used only in the following contexts:
in the body of an instance method or default method (8.4.7, 9.4.3)
in the body of a constructor of a class (8.8.7)
in an instance initializer of a class (8.6)
in the initializer of an instance variable of a class (8.3.2)
to denote a receiver parameter (8.4)
If it appears anywhere else, a compile-time error occurs.
The keyword this
may be used in a lambda expression only if it is allowed in the context in which the lambda expression appears. Otherwise, a compile-time error occurs.
When used as a primary expression, the keyword this
denotes a value that is a reference to the object for which the instance method or default method was invoked (15.12), or to the object being constructed. The value denoted by this
in a lambda body is the same as the value denoted by this
in the surrounding context.
The keyword
this
is also used in explicit constructor invocation statements (8.8.7.1).
The type of Let C be the innermost enclosing class or interface declaration of a this
is the class or interface type T within which the keyword this
occurs.this
expression. If C is generic, with type parameters F1, ..., Fn, the type of this
is C<F1, ..., Fn>. Otherwise, the type of this
is C.
Default methods provide the unique ability to accessthis
inside an interface. (All other interface methods are eitherabstract
orstatic
, so provide no access tothis
.) As a result, it is possible forthis
to have an interface type.
It's now default methods and private methods. But this comment was interesting when default methods were introduced; now it's just restating the obvious: interfaces can have instance methods with bodies.
At run time, the class of the actual object referred to may be T C, if T C is a class type, or a class that is a subtype of T subclass of C.
Example 15.8.3-1. The this
Expression
class IntVector {
int[] v;
boolean equals(IntVector other) {
if (this == other)
return true;
if (v.length != other.v.length)
return false;
for (int i = 0; i < v.length; i++) {
if (v[i] != other.v[i]) return false;
}
return true;
}
}
Here, the class IntVector
implements a method equals
, which compares two vectors. If the other vector is the same vector object as the one for which the equals
method was invoked, then the check can skip the length and value comparisons. The equals
method implements this check by comparing the reference to the other object to this
.
15.8.4 Qualified this
Any lexically enclosing instance (8.1.3) can be referred to by explicitly qualifying the keyword this
.
Let T be the type denoted by TypeName. Let n be an integer such that T TypeName is the n'th lexically enclosing type class or interface declaration of the class or interface in which the qualified this
expression appears.
The value of an expression of the form TypeName.this
is the n'th lexically enclosing instance of this
.
If TypeName is generic, with type parameters F1, ..., Fn, the type of the expression is TypeName<F1, ..., Fn>. The Otherwise, the type of the expression is C TypeName.
It is a compile-time error if TypeName is not a lexically enclosing class or interface declaration of the expression, or if the expression occurs in a class or interface which is not an inner class of class T TypeName or T TypeName itself.
15.9 Class Instance Creation Expressions
15.9.1 Determining the Class being Instantiated
If ClassOrInterfaceTypeToInstantiate ends with TypeArguments (rather than <>
), then ClassOrInterfaceTypeToInstantiate must denote a well-formed parameterized type (4.5), or a compile-time error occurs.
If ClassOrInterfaceTypeToInstantiate ends with <>
, but the type class or interface denoted by the Identifier in ClassOrInterfaceTypeToInstantiate is not generic, then a compile-time error occurs.
If the class instance creation expression ends in a class body, then the class being instantiated is an anonymous class. Then:
If the class instance creation expression is unqualified, then:
The Identifier in ClassOrInterfaceTypeToInstantiate must denote either a class that is accessible, non-
final
, and not an enumtypeclass, or an interface that is accessible (6.6). Otherwise a compile-time error occurs.If the Identifier in ClassOrInterfaceTypeToInstantiate denotes a class, C, then an anonymous direct subclass of C is declared. If TypeArguments is present, then C has type arguments given by TypeArguments; if
<>
is present, then C will have its type arguments inferred in 15.9.3; otherwise, C has no type arguments. The body of the subclass is the ClassBody given in the class instance creation expression. The class being instantiated is the anonymous subclass.If the Identifier in ClassOrInterfaceTypeToInstantiate denotes an interface, I, then an anonymous direct subclass of
Object
that implements I is declared. If TypeArguments is present, then I has type arguments given by TypeArguments; if<>
is present, then I will have its type arguments inferred in 15.9.3; otherwise, I has no type arguments. The body of the subclass is the ClassBody given in the class instance creation expression. The class being instantiated is the anonymous subclass.If the class instance creation expression is qualified, then:
The Identifier in ClassOrInterfaceTypeToInstantiate must unambiguously denote an inner class that is accessible, non-
final
, not an enumtypeclass, and a member of the compile-time type of the Primary expression or the ExpressionName. Otherwise, a compile-time error occurs.Let the Identifier in ClassOrInterfaceTypeToInstantiate denote a class, C. An anonymous direct subclass of C is declared. If TypeArguments is present, then C has type arguments given by TypeArguments; if
<>
is present, then C will have its type arguments inferred in 15.9.3; otherwise, C has no type arguments. The body of the subclass is the ClassBody given in the class instance creation expression. The class being instantiated is the anonymous subclass.
If a class instance creation expression does not declare an anonymous class, then:
If the class instance creation expression is unqualified, then:
The Identifier in ClassOrInterfaceTypeToInstantiate must denote a class that is accessible, non-
abstract
, and not an enumtypeclass. Otherwise, a compile-time error occurs.The class being instantiated is specified by the Identifier in ClassOrInterfaceTypeToInstantiate. If TypeArguments is present, then the class has type arguments given by TypeArguments; if
<>
is present, then the class will have its type arguments inferred in 15.9.3; otherwise, the class has no type arguments.If the class instance creation expression is qualified, then:
The ClassOrInterfaceTypeToInstantiate must unambiguously denote an inner class that is accessible, non-
abstract
, not an enumtypeclass, and a member of the compile-time type of the Primary expression or the ExpressionName.The class being instantiated is specified by the Identifier in ClassOrInterfaceTypeToInstantiate. If TypeArguments is present, then the class has type arguments given by TypeArguments; if
<>
is present, then the class will have its type arguments inferred in 15.9.3; otherwise, the class has no type arguments.
15.9.2 Determining Enclosing Instances
Let C be the class being instantiated, and let i be the instance being created. If C is an inner class, then i may have an immediately enclosing instance (8.1.3), determined as follows:
If C is an anonymous class, then:
If the class instance creation expression occurs in a static context, then i has no immediately enclosing instance.
Otherwise, the immediately enclosing instance of i is
this
.
If C is a local class, then:
If C occurs in a static context, then i has no immediately enclosing instance.
Otherwise, if the class instance creation expression occurs in a static context, then a compile-time error occurs.
Otherwise, let O be the immediately enclosing class or interface declaration of C. Let n be an integer such that O is the n'th lexically enclosing
typeclass or interface declaration of the class or interface in which the class instance creation expression appears.The immediately enclosing instance of i is the n'th lexically enclosing instance of
this
.
If C is an inner member class, then:
If the class instance creation expression is unqualified, then:
If the class instance creation expression occurs in a static context, then a compile-time error occurs.
Otherwise, if C is a member of a class enclosing the class or interface in which the class instance creation expression appears, then let O be the immediately enclosing class of which C is a member. Let n be an integer such that O is the n'th lexically enclosing
typeclass or interface declaration of the class or interface in which the class instance creation expression appears.The immediately enclosing instance of i is the n'th lexically enclosing instance of
this
.Otherwise, a compile-time error occurs.
If the class instance creation expression is qualified, then the immediately enclosing instance of i is the object that is the value of the Primary expression or the ExpressionName.
If C is an anonymous class, and its direct superclass S is an inner class, then i may have an immediately enclosing instance with respect to S, determined as follows:
If S is a local class, then:
If S occurs in a static context, then i has no immediately enclosing instance with respect to S.
Otherwise, if the class instance creation expression occurs in a static context, then a compile-time error occurs.
Otherwise, let O be the immediately enclosing
typeclass or interface declaration of S. Let n be an integer such that O is the n'th lexically enclosingtypeclass or interface declaration of the class or interface in which the class instance creation expression appears.The immediately enclosing instance of i with respect to S is the n'th lexically enclosing instance of
this
.
If S is an inner member class, then:
If the class instance creation expression is unqualified, then:
If the class instance creation expression occurs in a static context, then a compile-time error occurs.
Otherwise, if S is a member of a class enclosing the class or interface in which the class instance creation expression appears, then let O be the immediately enclosing class of which S is a member. Let n be an integer such that O is the n'th lexically enclosing
typeclass or interface declaration of the class or interface in which the class instance creation expression appears.The immediately enclosing instance of i with respect to S is the n'th lexically enclosing instance of
this
.Otherwise, a compile-time error occurs.
If the class instance creation expression is qualified, then the immediately enclosing instance of i with respect to S is the object that is the value of the Primary expression or the ExpressionName.
15.9.3 Choosing the Constructor and its Arguments
Let C be the class being instantiated. To create an instance of C, i, a constructor of C is chosen at compile time by the following rules.
First, the actual arguments to the constructor invocation are determined:
If C is an anonymous class with direct superclass S, then:
If S is not an inner class, or if S is a local class that occurs in a static context, then the arguments to the constructor are the arguments in the argument list of the class instance creation expression, if any, in the order they appear in the expression.
Otherwise, the first argument to the constructor is the immediately enclosing instance of i with respect to S (15.9.2), and the subsequent arguments to the constructor are the arguments in the argument list of the class instance creation expression, if any, in the order they appear in the class instance creation expression.
If C is a local class or a
private
inner member class, then the arguments to the constructor are the arguments in the argument list of the class instance creation expression, if any, in the order they appear in the class instance creation expression.If C is a non-
private
inner member class, then the first argument to the constructor is the immediately enclosing instance of i (8.8.1, 15.9.2), and the subsequent arguments to its constructor are the arguments in the argument list of the class instance creation expression, if any, in the order they appear in the class instance creation expression.Otherwise, the arguments to the constructor are the arguments in the argument list of the class instance creation expression, if any, in the order they appear in the expression.
Second, a constructor of C and corresponding throws
clause and return type are determined:
If the class instance creation expression does not use
<>
, then:If C is not an anonymous class, then:
Let T be the type denoted by C followed by any class type arguments in the expression. The process specified in 15.12.2, modified to handle constructors, is used to choose one of the constructors of T and determine its
throws
clause.If there is no unique most-specific constructor in T that is both applicable and accessible (6.6), then a compile-time error occurs (as in method invocations).
Otherwise, the return type corresponding to the chosen constructor is T.
If C is an anonymous class, then:
The process specified in 15.12.2, modified to handle constructors, is used to choose one of the constructors of the direct superclass type of C and determine its
throws
clause.If there is no unique most-specific constructor in the direct superclass type of C that is both applicable and accessible, then a compile-time error occurs (as in method invocations).
Otherwise, C's anonymous constructor is chosen as the constructor of C (15.9.5.1). Its body consists of an explicit constructor invocation (8.8.7.1) of the constructor chosen in the direct superclass type of C.
The
throws
clause of the chosen constructor includes the exceptions in thethrows
clause of the constructor chosen in the direct superclass type of C.The return type corresponding to the chosen constructor is the anonymous class type.
If the class instance creation expression uses
<>
, then:If C is not an anonymous class, let D be the same as C. If C is an anonymous class, let D be the superclass or superinterface of C named by the class instance creation expression.
In this case, we are in fact talking about a superclass or superinterface, not a superclass or superinterface type.
If D is a class, let c1...cn be the constructors of class D. If D is an interface, let c1...cn be a singleton list (n = 1) containing the zero-argument constructor of class
Object
.A list of methods m1...mn is defined for the purpose of overload resolution and type argument inference. For all j (1 ≤ j ≤ n), mj is defined in terms of cj as follows:
A substitution θj is first defined to instantiate the types in cj.
Let F1...Fp be the type parameters of D, and let G1...Gq be the type parameters (if any) of cj. Let X1...Xp and Y1...Yq be type variables with distinct names that are not in scope in the body of D.
θj is
[F1:=X1, ..., Fp:=Xp, G1:=Y1, ..., Gq:=Yq]
.The type parameters of mj are X1...Xp,Y1...Yq. The bound of each type parameter, if any, is θj applied to the corresponding type parameter bound in D or cj.
The return type of mj is θj applied to D
<
F1,...,Fp>
.The (possibly empty) list of argument types of mj is θj applied to the argument types of cj.
The (possibly empty) list of thrown types of mj is θj applied to the thrown types of cj.
The modifiers of mj are those of cj.
The name of mj is
#m
, an automatically generated name that is distinct from all constructor and method names in D and is shared by m1...mn.The body of mj is irrelevant.
To choose a constructor, we temporarily consider m1...mn to be members of D. One of m1...mn is chosen, as determined by the class instance creation expression's argument expressions, using the process specified in 15.12.2.
If there is no unique most specific method that is both applicable and accessible, then a compile-time error occurs.
Otherwise, where mj is the chosen method:
If C is not an anonymous class, then cj is chosen as the constructor of C.
The
throws
clause of the chosen constructor is the same as thethrows
clause determined for mj.The return type corresponding to the chosen constructor is the return type determined for mj (15.12.2.6).
If C is an anonymous class, then C's anonymous constructor is chosen as the constructor of C. Its body consists of an explicit constructor invocation (8.8.7.1) of cj.
The
throws
clause of the chosen constructor includes the exceptions in thethrows
clause determined for mj.The return type corresponding to the chosen constructor is the anonymous class type.
If the class instance creation expression is a poly expression, then its compatibility with a target type is as determined by 18.5.2.1, using mj as the selected method m.
Testing for compatibility with a target type may occur multiple times before making a final determination of the class instance creation expression's target type and the return type corresponding to the chosen constructor. For example, an enclosing method invocation expression may require testing the class instance creation expression for compatibility with different methods' formal parameter types.
If C is an anonymous class, then its direct superclass type or direct superinterface type (15.9.5) is the return type determined for mj (15.12.2.6).
It is a compile-time error if the direct superclass type or direct superinterface type, or any subexpression therein ("subexpression" includes type arguments of parameterized types, bounds of wildcard type arguments, and element types of array types, but excludes bounds of type variables), has one of the following forms:
A type variable that was not declared as a type parameter (such as a type variable produced by capture conversion).
An intersection type.
A class or interface type, where the class or interface declaration is not accessible from the class or interface in which the class instance creation expression appears.
It is a compile-time error if an argument to a class instance creation expression is not compatible with its target type, as derived from the invocation type (15.12.2.6).
If the compile-time declaration is applicable by variable arity invocation (15.12.2.4), then where the last formal parameter type of the invocation type of the constructor is Fn[]
, it is a compile-time error if the type which is the erasure of Fn is not accessible at the point of invocation.
The type of the class instance creation expression is the return type corresponding to the chosen constructor, as defined above.
15.9.4 Run-Time Evaluation of Class Instance Creation Expressions
At run time, evaluation of a class instance creation expression is as follows.
First, if the class instance creation expression is a qualified class instance creation expression, the qualifying primary expression is evaluated. If the qualifying expression evaluates to null
, a NullPointerException
is raised, and the class instance creation expression completes abruptly. If the qualifying expression completes abruptly, the class instance creation expression completes abruptly for the same reason.
Next, space is allocated for the new class instance. If there is insufficient space to allocate the object, evaluation of the class instance creation expression completes abruptly by throwing an OutOfMemoryError
.
The new object contains new instances of all the fields declared in the specified class type and all its superclasses. As each new field instance is created, it is initialized to its default value (4.12.5).
Next, the actual arguments to the constructor are evaluated, left-to-right. If any of the argument evaluations completes abruptly, any argument expressions to its right are not evaluated, and the class instance creation expression completes abruptly for the same reason.
Next, the selected constructor of the specified class type is invoked. This results in invoking at least one constructor for each superclass of the class type. This process can be directed by explicit constructor invocation statements (8.8.7.1) and is specified in detail in 12.5.
The value of a class instance creation expression is a reference to the newly created object of the specified class. Every time the expression is evaluated, a fresh object is created.
...
15.9.5 Anonymous Class Declarations
An anonymous class declaration is automatically derived from is implicitly declared by a class instance creation expression or an enum constant (8.9.1) that ends with a class body by the Java compiler.
An anonymous class is never abstract
(8.1.1.1).
An anonymous class declared by a class instance creation expression is never final
(8.1.1.2). An anonymous class declared by an enum constant is always final
.
There is a long history of efforts to make these rules more reasonable, which I believe were abandoned due to compatibility concerns. The above reflects the actual behavior of javac
in JDK 14.
The
fact that an anonymous class is nottreatment offinal
final
is relevant in casting, in particular the narrowing reference conversion allowed for the cast operator (5.5). It isalso of interest innot relevant to subclassing,in thatbecause it is impossible to declare a subclass of an anonymous class, despiteanthe anonymous class being non-final
, because an anonymous class cannot be named by anextends
clause (8.1.4).
An anonymous class is always an inner class (8.1.3); it is never .static
(8.1.1, 8.5.1)
The static
modifier is only meaningful to member classes. No need to mention it here, just like there's no mention of access control.
The direct superclass type or direct superinterface type of an anonymous class declared by a class instance creation expression is given by the class instance creation expression (15.9.1), with type arguments inferred as necessary while choosing a constructor (15.9.3). If a direct superinterface type is given, the direct superclass type is Object
.
The direct superclass type of an anonymous class declared by an enum constant is the type of the declaring enum class.
The ClassBody of the class instance creation expression or enum constant declares fields (8.3), methods (8.4), member classes (8.5), and instance initializers (8.6) of the anonymous class. The constructor of an anonymous class is always implicit (15.9.5.1).
If the class instance creation expression uses <>
with an anonymous class, then for all non-private
methods declared in the anonymous class body, it is as if the method declaration is annotated with @Override
(9.6.4.4).
When
<>
is used, the inferred type arguments may not be as anticipated by the programmer. Consequently, the supertype of the anonymous class may not be as anticipated, and methods declared in the anonymous class may not override supertype methods as intended. Treating such methods as if annotated with@Override
(if they are not explicitly annotated with@Override
) helps avoid silently incorrect programs.
15.9.5.1 Anonymous Constructors
An anonymous class cannot have an explicitly declared constructor. Instead, an anonymous constructor is implicitly declared for an anonymous class. The form of the anonymous constructor for an anonymous class C with direct superclass S A is as follows:
15.9.3 uses S to talk about the superclass type. Here, we want to talk about the class named by that type. It's helpful to distinguish the two by using a different letter, A.
If
SA is not an inner class, or ifSA is a local class that occurs in a static context, then the anonymous constructor has one formal parameter for each actual argument to the class instance creation expression or enum constant in which C is declared.The actual arguments to the class instance creation expression or enum constant are used to determine a constructor
csca ofSA, as specified by 15.9.3. The type of each formal parameter of the anonymous constructor must be identical to the corresponding formal parameter ofcsca.The constructor body consists of an explicit constructor invocation (8.8.7.1) of the form
super(...)
, where the actual arguments are the formal parameters of the constructor, in the order they were declared. The superclass constructor to be invoked iscsca.Otherwise, the first formal parameter of the constructor of C represents the value of the immediately enclosing instance of i with respect to
SA (15.9.2, 15.9.3). The type of this parameter is the class type that immediately encloses the declaration ofSA.The constructor has an additional formal parameter for each actual argument to the class instance creation expression that declared the anonymous class. The n'th formal parameter e corresponds to the n-1'th actual argument.
The actual arguments to the class instance creation expression are used to determine a constructor
csca ofSA, as specified by 15.9.3. The type of each formal parameter of the anonymous constructor must be identical to the corresponding formal parameter ofcsca.The constructor body consists of an explicit constructor invocation (8.8.7.1) of the form
o.super(...)
, whereo
is the first formal parameter of the constructor, and the actual arguments are the subsequent formal parameters of the constructor, in the order they were declared. The superclass constructor to be invoked iscsca.
In all cases, the throws
clause of an anonymous constructor must list lists all the checked exceptions thrown by the explicit superclass constructor invocation statement contained within the anonymous constructor, as specified in 15.9.3, and all checked exceptions thrown by any instance initializers or instance variable initializers of the anonymous class.
Note that it is possible for the signature of the anonymous constructor to refer to an inaccessible type (for example, if such a type occurred in the signature of the superclass constructor cs). This does not, in itself, cause any errors at either compile-time or run-time.
15.12 Method Invocation Expressions
15.12.1 Compile-Time Step 1: Determine Class or Interface Type to Search
The first step in processing a method invocation at compile time is to figure out the name of the method to be invoked and which class or interface type to search for definitions of methods of that name.
The name of the method is specified by the MethodName or Identifier which immediately precedes the left parenthesis of the MethodInvocation.
For the class or interface type to search, there are six cases to consider, depending on the form that precedes the left parenthesis of the MethodInvocation:
If the form is MethodName, that is, just an Identifier, then:
If the Identifier appears in the scope of a method declaration with that name (6.3, 6.4.1), then:
If there is an enclosing
typeclass or interface declaration of which that method is a member, letTE be the innermost suchtypeclass or interface declaration. Theclass or interfacetype to search isTthe type of E.this
(15.8.4).This search policy is called the "comb rule". It effectively looks for methods in a nested class's superclass hierarchy before looking for methods in an enclosing class and its superclass hierarchy. See 6.5.7.1 for an example.
Otherwise, the method declaration may be in scope due to one or more single-static-import or static-import-on-demand declarations. There is no
class or interfacetype to search, as the method to be invoked is determined later (15.12.2.1).
If the form is TypeName
.
[TypeArguments] Identifier, then the type to search is the (possibly raw) type denoted by TypeName.If the form is ExpressionName
.
[TypeArguments] Identifier, then theclass or interfacetype to search is the declared type T of the variable denoted by ExpressionName if T is a class or interface type, or the upper bound of T if T is a type variable.If the form is Primary
.
[TypeArguments] Identifier, then let T be the type of the Primary expression. Theclass or interfacetype to search is T if T is a class or interface type, or the upper bound of T if T is a type variable.It is a compile-time error if T is not a reference type.
If the form is
super
.
[TypeArguments] Identifier, then theclasstype to search is the direct superclass type of the class whose declaration contains the method invocation.Let
TE be thetype declarationclass or interface declaration immediately enclosing the method invocation. It is a compile-time error ifTE is the classObject
orTE is an interface.If the form is TypeName
.
super
.
[TypeArguments] Identifier, then:It is a compile-time error if TypeName denotes neither a class nor an interface.
If TypeName denote a class, C, then the
classtype to search is the direct superclass type of C.It is a compile-time error if C is not a lexically enclosing
typeclass or interface declaration of the current class or interface, or if C is the classObject
.Let
TE be thetypeclass or interface declaration immediately enclosing the method invocation. It is a compile-time error ifTE is the classObject
.Otherwise, TypeName denotes
the interface to be searchedan interface, I.Let
TE be thetypeclass or interface declaration immediately enclosing the method invocation.
It is a compile-time error if I is not a direct superinterface ofTE, or if there exists some other direct superclass or direct superinterface ofTE, J, such that J isa subtypea subclass or subinterface of I.The type to search is the type of I that is a direct superinterface type of E.
The TypeName
.
super
syntax is overloaded: traditionally, the TypeName refers to a lexically enclosingtypeclass declarationwhich is a class, and the target is the superclass of this class, as if the invocation were an unqualifiedsuper
in the lexically enclosingtypeclass declaration.class Superclass { void foo() { System.out.println("Hi"); } } class Subclass1 extends Superclass { void foo() { throw new UnsupportedOperationException(); } Runnable tweak = new Runnable() { void run() { Subclass1.super.foo(); // Gets the 'println' behavior } }; }
To support invocation of default methods in superinterfaces, the TypeName may also refer to a direct superinterface of the current class or interface, and the target is that superinterface.
interface Superinterface { default void foo() { System.out.println("Hi"); } } class Subclass2 implements Superinterface { void foo() { throw new UnsupportedOperationException(); } void tweak() { Superinterface.super.foo(); // Gets the 'println' behavior } }
No syntax supports a combination of these forms, that is, invoking a superinterface method of a lexically enclosing
typeclass declarationwhich is a class, as if the invocation were of the form InterfaceName.
super
in the lexically enclosingtypeclass declaration.class Subclass3 implements Superinterface { void foo() { throw new UnsupportedOperationException(); } Runnable tweak = new Runnable() { void run() { Subclass3.Superinterface.super.foo(); // Illegal } }; }
A workaround is to introduce a
private
method in the lexically enclosingtypeclass declaration,that performs the interfacesuper
call.
15.12.2 Compile-Time Step 2: Determine Method Signature
15.12.2.1 Identify Potentially Applicable Methods
The class or interface type determined by compile-time step 1 (15.12.1) is searched for all member methods that are potentially applicable to this method invocation; members inherited from superclasses and superinterfaces are included in this search.
...
15.12.3 Compile-Time Step 3: Is the Chosen Method Appropriate?
If there is a most specific method declaration for a method invocation, it is called the compile-time declaration for the method invocation.
It is a compile-time error if an argument to a method invocation is not compatible with its target type, as derived from the invocation type of the compile-time declaration.
If the compile-time declaration is applicable by variable arity invocation, then where the last formal parameter type of the invocation type of the method is Fn[]
, it is a compile-time error if the type which is the erasure of Fn is not accessible (6.6) at the point of invocation.
If the compile-time declaration is void
, then the method invocation must be a top level expression (that is, the Expression in an expression statement or in the ForInit or ForUpdate part of a for
statement), or a compile-time error occurs. Such a method invocation produces no value and so must be used only in a situation where a value is not needed.
In addition, whether the compile-time declaration is appropriate may depend on the form of the method invocation expression before the left parenthesis, as follows:
If the form is MethodName - that is, just an Identifier - and the compile-time declaration is an instance method, then:
It is a compile-time error if the method invocation occurs in a static context (8.1.3).
Otherwise, let C be the immediately enclosing class or interface declaration of which the compile-time declaration is a member. If the method invocation is not directly enclosed by C or an inner class of C, then a compile-time error occurs.
If the form is TypeName
.
[TypeArguments] Identifier, then the compile-time declaration must bestatic
, or a compile-time error occurs.If the form is ExpressionName
.
[TypeArguments] Identifier or Primary.
[TypeArguments] Identifier, then the compile-time declaration must not be astatic
method declared in an interface, or a compile-time error occurs.If the form is
super
.
[TypeArguments] Identifier, then:It is a compile-time error if the compile-time declaration is
abstract
.It is a compile-time error if the method invocation occurs in a static context.
If the form is TypeName
.
super
.
[TypeArguments] Identifier, then:It is a compile-time error if the compile-time declaration is
abstract
.It is a compile-time error if the method invocation occurs in a static context.
If TypeName denotes a class C, then if the method invocation is not directly enclosed by C or an inner class of C, a compile-time error occurs.
If TypeName denotes an interface, let
TE be thetypeclass or interface declaration immediately enclosing the method invocation. A compile-time error occurs if there exists a method, distinct from the compile-time declaration, that overrides (9.4.1) the compile-time declaration from a direct superclass or direct superinterface ofTE.In the case that a superinterface overrides a method declared in a grandparent interface, this rule prevents the child interface from "skipping" the override by simply adding the grandparent to its list of direct superinterfaces. The appropriate way to access functionality of a grandparent is through the direct superinterface, and only if that interface chooses to expose the desired behavior. (Alternately, the programmer is free to define an additional superinterface that exposes the desired behavior with a
super
method invocation.)
...
15.12.4.3 Check Accessibility of Type and Method
In this section:
Let D be the class containing the method invocation.
Let
TQ be the qualifyingtypeclass or interface of the method invocation (13.1).Let m be the name of the method as determined at compile time (15.12.3).
An implementation of the Java programming language must ensure, as part of linkage, that the type T class or interface Q is accessible:
If
TQ is in the same package as D, thenTQ is accessible.If
TQ is in a different package than D, and their packages are in the same module, andTQ ispublic
orprotected
, thenTQ is accessible.If
TQ is in a different package than D, and their packages are in different modules, andTQ's module exportsTQ's package to D's module, andTQ ispublic
orprotected
, thenTQ is accessible.
If
TQ isprotected
, it is necessarily a nestedtypeclass or interface, so at compile time, its accessibility is affected by the accessibility oftypesclasses and interfaces enclosing its declaration. However, during linkage, its accessibility is not affected by the accessibility oftypesclasses and interfaces enclosing its declaration. Moreover, during linkage, aprotected
TQ is as accessible as apublic
TQ. These discrepancies between access control at compile time (6.6) and access control at run time are due to limitations in the Java Virtual Machine.
The implementation must also ensure, during linkage, that the method m can still be found in T Q or a supertype superclass or superinterface of T Q. If m cannot be found, then a NoSuchMethodError
(which is a subclass of IncompatibleClassChangeError
) occurs. If m can be found, then let C be the type class or interface that declares m. The implementation must ensure, during linkage, that the declaration of m in C is accessible to D:
If m is
public
, then m is accessible.If m is
protected
, then m is accessible iff (i) either D is in the same package as C, or D is asubtypesubclass of C or C itself; and (ii) if m is aprotected
instance method, thenTQ must be asubtypesubclass of D or D itself.This is the only place where
TQ is involved in checks for m, because aprotected
instance method may only be invoked via a qualifyingtypeclass or interface that aligns with the invoker's type.If m has package access, then m is accessible iff D is in the same package as C.
If m is
private
, then m is accessible iff D is C, or D encloses C, or C encloses D, or C and D are both enclosed by a thirdtypeclass or interface.
If either T Q or m is not accessible, then an IllegalAccessError
occurs (12.3).
If the invocation mode is interface
, then the implementation must check that the target reference type class still implements the specified interface. If the target reference type class does not still implement the interface, then an IncompatibleClassChangeError
occurs.
15.12.4.4 Locate Method to Invoke
As in the previous section (15.12.4.3):
Let
TQ be the qualifyingtypeclass or interface of the method invocation (13.1).Let m be the method found in
TQ or asupertypesuperclass or superinterface ofTQ. (Note that m was merely the name of the method in the previous section; here it is the actual declaration.)Let C be the class or interface that declares m.
The strategy for locating a method to invoke depends on the invocation mode:
If the invocation mode is
static
, no target reference is needed and overriding is not allowed. Method m of class or interface C is the one to be invoked.Otherwise, an instance method is to be invoked and there is a target reference. If the target reference is
null
, aNullPointerException
is thrown at this point. Otherwise, the target reference is said to refer to a target object and will be used as the value of the keywordthis
in the invoked method. The other three possibilities for the invocation mode are then considered:If the invocation mode is
super
, overriding is not allowed. Method m of class or interface C is the one to be invoked. If m isabstract
, anAbstractMethodError
is thrown.Otherwise, if the invocation mode is
virtual
, and T and m jointly indicate a signature polymorphic method (15.12.3), then the target object is an instance ofjava.lang.invoke.MethodHandle
orjava.lang.invoke.VarHandle
. The target object encapsulates state which is matched against the information associated with the method invocation at compile time. Details of this matching are given in The Java Virtual Machine Specification, Java SE 15 Edition and the Java SE Platform API. If matching succeeds, then either the method referenced by thejava.lang.invoke.MethodHandle
instance is directly and immediately invoked, or the variable represented by thejava.lang.invoke.VarHandle
instance is directly and immediately accessed, and in either case the procedure in 15.12.4.5 is not executed. If matching fails, then ajava.lang.invoke.WrongMethodTypeException
is thrown.Otherwise, the invocation mode is
interface
orvirtual
.If the method m of class or interface C is
private
, then it is the method to be invoked.Otherwise, overriding may occur. A dynamic method lookup, specified below, is used to locate the method to invoke. The lookup procedure starts from class R, the actual run-time class of the target object.
Note that for invocation mode
interface
, R necessarily implementsTQ; for invocation modevirtual
, R is necessarily eitherTQ or a subclass ofTQ. If the target object is an array, then R is a "class" representing an array type.
...
15.13 Method Reference Expressions
A method reference expression is used to refer to the invocation of a method without actually performing the invocation. Certain forms of method reference expression also allow class instance creation (15.9) or array creation (15.10) to be treated as if it were a method invocation.
- MethodReference:
- ExpressionName
::
[TypeArguments] Identifier - Primary
::
[TypeArguments] Identifier - ReferenceType
::
[TypeArguments] Identifier super
::
[TypeArguments] Identifier- TypeName
.
super
::
[TypeArguments] Identifier - ClassType
::
[TypeArguments]new
- ArrayType
::
new
If TypeArguments is present to the right of ::
, then it is a compile-time error if any of the type arguments are wildcards (4.5.1).
If a method reference expression has the form ExpressionName ::
[TypeArguments] Identifier or Primary ::
[TypeArguments] Identifier, it is a compile-time error if the type of the ExpressionName or Primary is not a reference type.
If a method reference expression has the form super
::
[TypeArguments] Identifier, let T E be the type class or interface declaration immediately enclosing the method reference expression. It is a compile-time error if T E is the class Object
or T E is an interface.
If a method reference expression has the form TypeName .
super
::
[TypeArguments] Identifier, then:
If TypeName denotes a class, C, then it is a compile-time error if C is not a lexically enclosing class of the current class, or if C is the class
Object
.If TypeName denotes an interface, I, then let
TE be thetypeclass or interface declaration immediately enclosing the method reference expression. It is a compile-time error if I is not named by a direct superinterface type ofTE, or if there exists some other direct superclass type or direct superinterface type ofTE,naming a class or interface J, such that J is asubtypesubclass or subinterface of I.If TypeName denotes a type variable, then a compile-time error occurs.
If a method reference expression has the form super
::
[TypeArguments] Identifier or TypeName .
super
::
[TypeArguments] Identifier, it is a compile-time error if the expression occurs in a static context.
If a method reference expression has the form ClassType ::
[TypeArguments] new
, then:
ClassType must
denotename a class that is accessible (6.6), non-abstract
, and not an enumtypeclass, or a compile-time error occurs.If ClassType denotes a parameterized type (4.5), then it is a compile-time error if any of its type arguments are wildcards.
If ClassType denotes a raw type (4.8), then it is a compile-time error if TypeArguments is present after the
::
.
If a method reference expression has the form ArrayType ::
new
, then ArrayType must denote a type that is reifiable (4.7), or a compile-time error occurs.
...