This specification is not final and is subject to change. Use is subject to license terms.

Consistent Class and Interface Terminology

Changes to the Java® Language Specification • Version 16-internal+0-adhoc.gbierman.20201104

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]
[Superclass ClassExtends] [Superinterfaces ClassImplements] ClassBody

which 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:

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:

Given the generic types classes in the examples of 8.1.2, here are some well-formed parameterized types:

Here are some incorrect parameterizations of those generic types classes:

A parameterized type may be an a 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:

If any of the type arguments in the parameterization of C are wildcards, then:

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:

A The type of a non-generic class or interface type is not a raw type.

To see why a non-static type member the name of an inner member class of a raw type is considered raw, consider the following example:

class 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 of Outer. If Outer is raw, Inner must be treated as raw as well, as there is no valid binding for T.

This rule applies only to type members inner member classes that are not inherited. Inherited type members inner 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 including Inner, 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:

...

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:

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:

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:

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:

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:

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:

Also, types are used as:

Finally, there are three two special terms in the Java programming language which denote the use of a type:

The meaning of types in type contexts is given by:

Some type contexts restrict how a reference type may be parameterized:

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:

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 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:

and in expressions of the following kinds:

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:

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.

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:

The 14 non-generic contexts are as follows:

  1. In a uses or provides directive in a module declaration (7.7.1)

  2. In a single-type-import declaration (7.5.1)

  3. To the left of the . in a single-static-import declaration (7.5.3)

  4. To the left of the . in a static-import-on-demand declaration (7.5.4)

  5. To the left of the ( in a constructor declaration (8.8)

  6. After the @ sign in an annotation (9.7)

  7. To the left of .class in a class literal (15.8.2)

  8. To the left of .this in a qualified this expression (15.8.4)

  9. To the left of .super in a qualified superclass field access expression (15.11.2)

  10. To the left of .Identifier or .super.Identifier in a qualified method invocation expression (15.12)

  11. To the left of .super:: in a method reference expression (15.13)

  12. In a qualified expression name in a postfix expression or a try-with-resources statement (15.14.1, 14.20.3)

  13. In a throws clause of a method or constructor (8.4.6, 8.8.5, 9.4)

  14. 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 or catch 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> ... or interface C<T> ...) (8.1.2, 9.1.2) introduces both a class named C and a family of types: raw C, 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 to C denotes the class or interface C. In other contexts, the reference to C denotes a type, or part of a type, introduced by C.

The 14 non-generic contexts are as follows:

  1. In a uses or provides directive in a module declaration (7.7.1)

  2. In a single-type-import declaration (7.5.1)

  3. To the left of the . in a single-static-import declaration (7.5.3)

  4. To the left of the . in a static-import-on-demand declaration (7.5.4)

  5. To the left of the ( in a constructor declaration (8.8)

  6. After the @ sign in an annotation (9.7)

  7. To the left of .class in a class literal (15.8.2)

  8. To the left of .this in a qualified this expression (15.8.4)

  9. To the left of .super in a qualified superclass field access expression (15.11.2)

  10. To the left of .Identifier or .super.Identifier in a qualified method invocation expression (15.12)

  11. To the left of .super:: in a method reference expression (15.13)

  12. In a qualified expression name in a postfix expression or a try-with-resources statement (15.14.1, 14.20.3)

  13. In a throws clause of a method or constructor (8.4.6, 8.8.5, 9.4)

  14. 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 or catch 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 and cos methods of the class java.lang.Math have mathematically conventional names, even though these method names flout the convention suggested here because they are short and are not verbs.

...

Class and Interface Type Names

Names of class types classes 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 types interfaces should be short and descriptive, not overly long, in mixed case with the first letter of each word capitalized. The name may be a descriptive noun or noun phrase, which is appropriate when an interface is used as if it were an abstract superclass, such as interfaces java.io.DataInput and java.io.DataOutput; or it may be an adjective describing a behavior, as for the interfaces Runnable and Cloneable.

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 types classes and interfaces should use the name E for their element type. Maps should use K for the type of their keys and V for the type of their values. The name X should be used for arbitrary exception types. We use T 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 as S. 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 types interfaces should be, and final variables of class types classes may conventionally be, a sequence of one or more words, acronyms, or abbreviations, all uppercase, with components separated by underscore "_" characters. Constant names should be descriptive and not unnecessarily abbreviated. Conventionally they may be any appropriate part of speech.

Examples of names for constants include MIN_VALUE, MAX_VALUE, MIN_RADIX, and MAX_RADIX of the class Character.

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

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 types classes, 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:

...

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:

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:

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

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

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 term p.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 of p, q, and Foo is a type name or a package name.

As another example, suppose a cast operator uses the type p.q.Foo<? extends String>. The term p.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 term String is extracted as an Identifier in an extends 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:

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

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

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

The effect of syntactic classification is to restrict certain kinds of entities to certain parts of expressions:

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 type class or interface must be accessible from the compilation unit containing the import declaration. As another example, a class declaration may use a qualified type name for a superclass type (8.1.5), so again the named type class 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 types classes, 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 than that 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 type class, interface, or type parameter, there is the matter of access to constructors of a reference type class. 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 class type denoted by an unqualified class instance creation expression and a constructor of that class type. 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} { TypeDeclaration TopLevelClassOrInterfaceDeclaration }
ModularCompilationUnit:
{ImportDeclaration} ModuleDeclaration

An ordinary compilation unit consists of three parts, each of which is optional:

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 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/type names 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:

ImportDeclaration:
SingleTypeImportDeclaration
TypeImportOnDemandDeclaration
SingleStaticImportDeclaration
StaticImportOnDemandDeclaration

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 makes types classes, interfaces, or members available by their simple names only within the compilation unit that actually contains the import declaration. The scope of the type(s) class(es), interface(s), or member(s) introduced by an import declaration specifically does not include other compilation units in the same package, other import declarations in the current compilation unit, or a package declaration in the current compilation unit (except for the annotations of a package 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 of type class 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 name java.util.Vector refer to the same type class.

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:

This restriction implies that there must be at most one such type class 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 interface type in its own compilation unit, whether or not it is public or is referred to by code in other compilation units.

For example, the source code for a public type wet.sprocket.Toad would be found in a file Toad.java in the directory wet/sprocket, and the corresponding object code would be found in the file Toad.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 public, and that is top level or nested 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 public, then it can be referred to from code in any package of its module and potentially from code in other modules. A class can use access control (6.6) to prevent references to the class from other classes, interfaces, packages, or modules. Each class except 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]
[Superclass ClassExtends] [Superinterfaces ClassImplements] 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 type class 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 Enum, which can only be extended by an enum class (8.9).

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:

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:

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 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:

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:

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:

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 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 itself is 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 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:

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:

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:

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 the abstract 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:

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:

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:

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:

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:

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:

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 declaration class or interface cannot implement or extend two distinct invocations parameterizations 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:

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 a private method in one of its superclasses, and there is no requirement that the return type or throws clause of such a method bear any relationship to those of the private 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.)

This is already stated in 8.1.1 and 9.1.1.

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 types classes 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:

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 a superclass constructor invocation statement is qualified, then:

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:

  1. 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 type class 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 type class 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, a NullPointerException 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.

  2. 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.

  3. 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 [Superinterfaces ClassImplements] 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 type class in the body of as a member of an inner class (8.1.3), because an inner class cannot have static 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 type class exist beyond those defined by its enum constants:

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 in Enum is a final method that merely invokes super.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 type class by declaring String and int parameters in the default constructor of an enum type class. 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 enum type declaration knows how to instantiate the enum constants; other compilers can simply rely on the implicitly declared public static fields of the enum type class (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:

It follows that the declaration of enum type class 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 override final methods of class Enum<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]
[ExtendsInterfaces InterfaceExtends] 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:

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.

Presentational changes in these definitions to align with 8.1.4 and 8.1.5.

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:

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:

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:

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 inherits name() from Top, but Bottom inherits name() from Left, not Right. This is because name() from Left overrides the declaration of name() in Top.

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 a static 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 a static method", whereas the rule above speaks only of an interface that "declares a static method", since an interface cannot inherit a static method. Also note that the rule in 8.4.8.2 allows hiding of both instance and static methods in superclasses/superinterfaces, whereas the rule above considers only public instance methods in superinterfaces superinterface types.

Along the same lines, a private method in an interface cannot override an instance method - whether public or private - in a superinterface type. This is similar to the rules in 8.4.8.1 and 8.4.8.3 whereby a private 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, only public methods in interfaces can be overridden, and only by public 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:

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.

This is already stated in 8.1.1 and 9.1.1.

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-private member 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 TypeIdentifier AnnotationTypeBody AnnotationInterfaceBody

Note that the at-sign at sign (@) and the keyword interface 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 AnnotationTypeDeclaration AnnotationInterfaceDeclaration syntax, an annotation type interface declaration cannot be generic, and no extends clause is permitted.

A consequence of the fact that an annotation type interface cannot explicitly declare a superclass type or superinterface type is that a subclass or subinterface of an annotation type interface is never itself an annotation type interface. Similarly, java.lang.annotation.Annotation is not itself an annotation type interface.

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 type interface, 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 types interfaces share the same namespace as normal class and interface types classes and interfaces; and annotation type declarations are legal wherever interface declarations are legal, and have 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:
{ { AnnotationTypeMemberDeclaration AnnotationMemberDeclaration } }
AnnotationTypeMemberDeclaration: AnnotationMemberDeclaration:
AnnotationTypeElementDeclaration AnnotationElementDeclaration
ConstantDeclaration
ClassDeclaration
InterfaceDeclaration
;
AnnotationTypeElementDeclaration: AnnotationElementDeclaration:
{ AnnotationTypeElementModifier AnnotationElementModifier } UnannType Identifier ( ) [Dims]
[DefaultValue] ;
AnnotationTypeElementModifier: AnnotationElementModifier:
(one of)
Annotation public
abstract

By virtue of the AnnotationTypeElementDeclaration AnnotationElementDeclaration production, a method declaration in an annotation type declaration cannot have formal parameters, type parameters, or a throws clause. The following production from 4.3 is shown here for convenience:

Dims:
{Annotation} [ ] {{Annotation} [ ]}

By virtue of the AnnotationTypeElementModifier AnnotationElementModifier production, a method declaration in an annotation type declaration cannot be default or static. Thus, an annotation type interface cannot declare the same variety of methods as a normal interface type. Note that it is still possible for an annotation type interface 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 AnnotationTypeElementModifiers AnnotationElementModifiers that should be present on an annotation type element 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:

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:

  1. TC AC declares a value() method element whose return type is T[] A[].

  2. Any methods elements declared by TC AC other than value() have a default value.

  3. TC AC is retained for at least as long as T A, where retention is expressed explicitly or implicitly with the @Retention annotation (9.6.4.2). Specifically:

    • If the retention of TC AC is java.lang.annotation.RetentionPolicy.SOURCE, then the retention of T A is java.lang.annotation.RetentionPolicy.SOURCE.

    • If the retention of TC AC is java.lang.annotation.RetentionPolicy.CLASS, then the retention of T A is either java.lang.annotation.RetentionPolicy.CLASS or java.lang.annotation.RetentionPolicy.SOURCE.

    • If the retention of TC AC is java.lang.annotation.RetentionPolicy.RUNTIME, then the retention of T A is java.lang.annotation.RetentionPolicy.SOURCE, java.lang.annotation.RetentionPolicy.CLASS, or java.lang.annotation.RetentionPolicy.RUNTIME.

  4. T A is applicable to at least the same kinds of program element as TC AC (9.6.4.1). Specifically, if the kinds of program element where T A is applicable are denoted by the set m1, and the kinds of program element where TC AC 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 of java.lang.annotation.ElementType.ANNOTATION_TYPE or java.lang.annotation.ElementType.TYPE or java.lang.annotation.ElementType.TYPE_USE must occur in m1.

    • If the kind in m2 is java.lang.annotation.ElementType.TYPE, then at least one of java.lang.annotation.ElementType.TYPE or java.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 of java.lang.annotation.ElementType.TYPE_PARAMETER or java.lang.annotation.ElementType.TYPE_USE must occur in m1.

    This clause implements the policy that an annotation type interface may be repeatable on only some of the kinds of program element where it is applicable.

  5. If the declaration of T A has a (meta-)annotation that corresponds to java.lang.annotation.Documented, then the declaration of TC AC must have a (meta-)annotation that corresponds to java.lang.annotation.Documented.

    Note that it is permissible for TC AC to be @Documented while T A is not @Documented.

  6. If the declaration of T A has a (meta-)annotation that corresponds to java.lang.annotation.Inherited, then the declaration of TC AC must have a (meta)-annotation that corresponds to java.lang.annotation.Inherited.

    Note that it is permissible for TC AC to be @Inherited while T A 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 type interface to be specified would cause an undesirable choice at compile time, when multiple annotations of the repeatable annotation type interface 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 T interface A specifies a containing annotation type interface of TC AC, then the value() method of TC AC has a return type involving T A, specifically T[] A[].

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 annotation type interface. Specifically, if an annotation type interface A specified itself (via @Repeatable) as its containing annotation type interface, then the return type of A's value() method would have to be A[]; but this would cause a compile-time error since an annotation type interface cannot refer to itself in its elements (9.6.1). More generally, two annotation types interfaces cannot specify each other to be their containing annotation types interfaces, because cyclic annotation type interface 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:

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:

  1. Module declarations (7.7)

    Corresponds to java.lang.annotation.ElementType.MODULE

  2. Package declarations (7.4.1)

    Corresponds to java.lang.annotation.ElementType.PACKAGE

  3. Type declarations: class, interface, enum, and annotation type declarations (8.1.1, 9.1.1, 8.5, 9.5, 8.9, 9.6)

    Corresponds to java.lang.annotation.ElementType.TYPE

    Additionally, annotation type declarations correspond to java.lang.annotation.ElementType.ANNOTATION_TYPE

  4. Method declarations (including elements of annotation types interfaces) (8.4.3, 9.4, 9.6.1)

    Corresponds to java.lang.annotation.ElementType.METHOD

  5. Constructor declarations (8.8.3)

    Corresponds to java.lang.annotation.ElementType.CONSTRUCTOR

  6. 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

  7. Field declarations (including enum constants) (8.3.1, 9.3, 8.9.1)

    Corresponds to java.lang.annotation.ElementType.FIELD

  8. Formal and exception parameter declarations (8.4.1, 9.4, 14.20)

    Corresponds to java.lang.annotation.ElementType.PARAMETER

  9. Local variable declarations (including loop variables of for statements and resource variables of try-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 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 class Foo:

public boolean equals(Foo that) { ... }

when they mean to write:

public boolean equals(Object that) { ... }

This is perfectly legal, but class Foo inherits the equals implementation from Object, 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 following type declarations:

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, because Foo.hashCode overrides from Foo the method Object.hashCode.

For the interface declaration, consider that while an interface does not have Object as a supertype, an interface does have public abstract members that correspond to the public members of Object (9.2). If an interface chooses to declare them explicitly (that is, to declare members that are override-equivalent to public methods of Object), then the interface is deemed to override them, and use of @Override is allowed.

However, consider an interface that attempts to use @Override on a clone method: (finalize could also be used in this example)

interface Quux { @Override Object clone(); }

Because Object.clone is not public, there is no member called clone implicitly declared in Quux. Therefore, the explicit declaration of clone in Quux is not deemed to "implement" any other method, and it is erroneous to use @Override. (The fact that Quux.clone is public is not relevant.)

In contrast, a class declaration that declares clone is simply overriding Object.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:

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:

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:

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:

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 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 type interface and TC is its containing annotation type interface, 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 annotation type interface without deprecating the corresponding repeatable annotation type interface.

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 like java.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 for java.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 to static methods, final and/or private 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 annotation type interface of T. There are numerous well-formedness rules for TC to be considered the containing annotation type interface 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:

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 type declaration.

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 type interface S with a meta-annotation of type interface T, and to annotate T's own declaration with a meta-annotation of type interface S. The pre-defined annotation types interfaces 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 on f if Foo is meta-annotated by @Target(ElementType.FIELD), and a type annotation on int if Foo 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, and C are annotation types interfaces meta-annotated with @Target(ElementType.TYPE_USE), then given the field declaration:

@C int @A [] @B [] f;

@A applies to the array type int[][], @B applies to its component type int[], and @C applies to the element type int. 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 type int 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:

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:

In the second and third cases above, the type which is closest to the annotation is determined as follows:

It is a compile-time error if an annotation of type T interface A is syntactically a modifier for:

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 type declarations, and for type parameter declarations - mention "... or type contexts" because it may be convenient to apply an annotation whose type interface is meta-annotated with @Target(ElementType.TYPE_USE) (thus, applicable in type contexts) to a type class, interface, or type parameter declaration.

A type annotation is admissible if both of the following are true:

The intuition behind the second clause is that if Outer.this is legal in a nested class enclosed by Outer, then Outer may be annotated because it represents the type of some object at run time. On the other hand, if Outer.this is not legal - because the class where it appears has no enclosing instance of Outer at run time - then Outer 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 of B, as B has no lexically enclosing instances (8.5.1). Therefore, it is not possible to apply @Foo to A in the type A.B, because A 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 of D. Therefore, it is possible to apply @Foo to C in the type C.D, because C 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 type interface TA which is meta-annotated with just @Target(ElementType.TYPE_USE). The terms @TA java.lang.Object and java.@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 of f (and not to the type java.lang.Object) because TA 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 type interface 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 type interface 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 type interface Foo would be contained by an implicitly declared container annotation of type interface FooContainer, then that annotation and the explicitly declared annotation of type interface FooContainer 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 of type interface Foo 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 type interface Foo, no container annotation is implicitly declared, even if FooContainer is the containing annotation type interface of Foo. However, repeating the annotation of type interface FooContainer, as in:

@Foo(1) @FooContainer({@Foo(2)}) @FooContainer({@Foo(3)})
class A {}

is prohibited, even if FooContainer is repeatable with a containing annotation type interface of its own. It is obtuse to repeat annotations which are themselves containers when an annotation of the underlying repeatable type interface 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:

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 and SecurityManager.

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:

  1. The class or interface must be named by its binary name, which must meet the following constraints:

    • The binary name of a top level type class or interface (7.6) is its canonical name (6.7).

    • The binary name of a member type class or interface (8.5, 9.5) consists of the binary name of its immediately enclosing type class 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 type class 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 type class 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 type class 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 type class 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 type class 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...

  2. A reference to another class or interface type must be symbolic, using the binary name of the type class or interface.

  3. 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 only static fields.) The class should have code to set the field's value to V during instance creation (12.5).

  4. 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 type class 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 T Q be C. Otherwise, let T Q be the innermost lexically enclosing type class or interface declaration of which f is a member. In either case, T Q is the qualifying type class 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 qualifying type class 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 qualifying type class 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 type class or interface of the reference.

    • If the expression is of the form super.f, then the superclass of C is the qualifying type class 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 qualifying type class or interface of the reference.

    The reference to f must be compiled into a symbolic reference to the erasure (4.6) of the qualifying type class 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.

  5. 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 type class or interface of the method invocation as follows:

    • If D is Object then the qualifying type class or interface of the expression is Object.

    • Otherwise:

      • If the method is referenced by a simple name, then if m is a member of the current class or interface C, let T Q be C; otherwise, let T Q be the innermost lexically enclosing type class or interface declaration of which m is a member. In either case, T Q is the qualifying type class or interface of the method invocation.

      • If the expression is of the form TypeName.m or ReferenceType::m, then the type class or interface denoted by TypeName, or the erasure (4.6) of ReferenceType, is the qualifying type class 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 qualifying type class 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 type class or interface of the method invocation.

      • If the expression is of the form super.m or super::m, then the superclass of C is the qualifying type class 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 qualifying type class or interface of the method invocation; if TypeName denotes an interface X, X is the qualifying type class 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 the qualifying type class 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.

  6. 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 qualifying type class 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 qualifying type class of the invocation is D.

    • If the expression is of the form new D(...){...} or ExpressionName.new D(...){...} or Primary.new D(...){...}, then the qualifying type class of the expression is the compile-time type of anonymous class declared by the expression.

    • If the expression is of the form super(...) or ExpressionName.super(...) or Primary.super(...), then the qualifying type class of the expression is the direct superclass of C.

    • If the expression is of the form this(...), then the qualifying

    • type class 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 the qualifying type class 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:

  1. If it is a class and is not Object, then a symbolic reference to the erasure of the direct superclass of this class.

  2. A symbolic reference to the erasure of each direct superinterface, if any.

  3. 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.

  4. If it is a class, then the erased signature of each constructor, as described above.

  5. 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.

  6. 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.

  7. Every type class or interface must contain sufficient information to recover its canonical name (6.7).

  8. Every member type class or interface must have sufficient information to recover its source-level access modifier.

  9. Every nested class and nested or interface must have a symbolic reference to its immediately enclosing type class or interface (8.1.3).

  10. Every class or interface must contain symbolic references to all of its member types classes and interfaces (8.5, 9.5), and to all local and anonymous classes that appear in its methods, constructors, static initializers, instance initializers, and field initializers other 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.

  11. 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).

  12. 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:

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:

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 and ExceptionB do not have a subclass/superclass relationship when the client is compiled, it is binary compatible with respect to the client for ExceptionA and ExceptionB 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:

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:

...

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:

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 this is the class or interface type T within which the keyword this occurs. Let C be the innermost enclosing class or interface declaration of a 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 access this inside an interface. (All other interface methods are either abstract or static, so provide no access to this.) As a result, it is possible for this 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 a class instance creation expression does not declare an anonymous class, then:

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, and its direct superclass S is an inner class, then i may have an immediately enclosing instance with respect to S, determined as follows:

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:

Second, a constructor of C and corresponding throws clause and return type are determined:

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 not final treatment of final is relevant in casting, in particular the narrowing reference conversion allowed for the cast operator (5.5). It is also of interest in not relevant to subclassing, in that because it is impossible to declare a subclass of an anonymous class, despite an the anonymous class being non-final, because an anonymous class cannot be named by an extends 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.

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:

The TypeName . super syntax is overloaded: traditionally, the TypeName refers to a lexically enclosing type class declaration which is a class, and the target is the superclass of this class, as if the invocation were an unqualified super in the lexically enclosing type class 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 type class declaration which is a class, as if the invocation were of the form InterfaceName . super in the lexically enclosing type class 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 enclosing type class declaration, that performs the interface super 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:

...

15.12.4.3 Check Accessibility of Type and Method

In this section:

An implementation of the Java programming language must ensure, as part of linkage, that the type T class or interface Q is accessible:

If T Q is protected, it is necessarily a nested type class or interface, so at compile time, its accessibility is affected by the accessibility of types classes and interfaces enclosing its declaration. However, during linkage, its accessibility is not affected by the accessibility of types classes and interfaces enclosing its declaration. Moreover, during linkage, a protected T Q is as accessible as a public T Q. 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 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):

The strategy for locating a method to invoke depends on the invocation mode:

...

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 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:

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.

...