Consistent Class and Interface Terminology

Changes to the Java® Language Specification • Version 15+36-1562

This document describes changes to the Java Language Specification to clarify the usage of terms related to classes and interfaces, and more clearly distinguish them from types.

The following terminology is preferred: a class or interface declaration is a syntactic structure that introduces a class or an interface. Various class and interface declarations have different syntactic forms, and can appear in different contexts, per the grammar. A class type or an interface type is variable or expression type, derived from a class or an interface; these terms should be avoided when talking about the declaration. An enum declaration is a kind of class declaration that introduces a special kind of class, an enum class. An annotation declaration is a kind of interface declaration that introduces a special kind of interface, an annotation interface.

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 may be generic, that is, they may be parameterized by other reference types. Such declarations may then be invoked with 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 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 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 class or of any subclass of that class, allowing new types 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 on other types that use the changed types but have not been recompiled. These considerations are of interest to developers of types 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 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 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.

...

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 types. 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 or superinterface 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 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.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 class, interface, or type parameter in a package uniquely visible to the current module, or the name of a package uniquely visible to the current module (7.4.3).

To do: this doesn't seem right—e.g., a local class or a type parameter isn't a member of a package at all. Shouldn't any external package be handled by checking an import statement?

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.

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 declared in another package, or a static member of another type, is to use a fully qualified name (6.7) a reference to a class or interface declared in another package, or a static member of another class or interface, would typically need to use a 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), which may be an enum class (8.9), or a top level interface type (9 9.1), which may be an annotation interface (9.6).

TypeDeclaration: TopLevelClassOrInterfaceDeclaration:
ClassDeclaration
InterfaceDeclaration
ClassOrInterfaceDeclaration
;
ClassOrInterfaceDeclaration:
ClassDeclaration
EnumDeclaration
InterfaceDeclaration
AnnotationDeclaration

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.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 or an interface, and not an enum class. It is a compile-time error if a provides directive specifies an enum type class (8.9) as the service.

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

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 member classes and interface members member 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).

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: ClassDeclaration:
{ClassModifier} class TypeIdentifier [TypeParameters]
[Superclass] [Superinterfaces] ClassBody

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.

Enum classes are a kind of class, but enum declarations are a separate syntactic construct—there's no particular reason to group them together here.

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

We're talking about the ClassModifier production that appears in the ClassDeclaration syntax, which is shared by top level, member, and local classes. There is no ClassModifier production in an anonymous class declaration, so it doesn't make sense to mention such classes here.

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 class 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 type 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 or interface declaration. An instance variable is always defined with respect to an instance. In the case of instance variables of an enclosing type class or interface declaration, the instance variable must be defined with respect to an enclosing instance of that declared type class or interface. 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.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), and 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
ClassOrInterfaceDeclaration
;

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.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 is specified in 6.3 and 6.4.

This is already stated in 8.1 and 9.1.

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] 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 declaration 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).

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.

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
ClassOrInterfaceDeclaration
;

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. 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 abstract reference type 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, 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. There are two kinds of interface declarations - normal interface declarations and annotation type declarations (9.6).

InterfaceDeclaration:
NormalInterfaceDeclaration
AnnotationTypeDeclaration
NormalInterfaceDeclaration: InterfaceDeclaration:
{InterfaceModifier} interface TypeIdentifier [TypeParameters]
[ExtendsInterfaces] InterfaceBody

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.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), and classes (9.5), and interfaces (9.5).

InterfaceBody:
{ {InterfaceMemberDeclaration} }
InterfaceMemberDeclaration:
ConstantDeclaration
InterfaceMethodDeclaration
ClassDeclaration
InterfaceDeclaration
ClassOrInterfaceDeclaration
;

The scope of a declaration of a member m declared in or inherited by an interface type I is specified in 6.3.

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 of every annotation type interface is java.lang.annotation.Annotation.

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 or superinterface 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
ClassOrInterfaceDeclaration
;
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 interface T 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.

An annotation type interface TC is a containing annotation type interface of T if all of the following are true:

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

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

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

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

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

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

  4. T is applicable to at least the same kinds of program element as TC (9.6.4.1). Specifically, if the kinds of program element where T is applicable are denoted by the set m1, and the kinds of program element where TC 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 has a (meta-)annotation that corresponds to java.lang.annotation.Documented, then the declaration of TC must have a (meta-)annotation that corresponds to java.lang.annotation.Documented.

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

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

    Note that it is permissible for TC to be @Inherited while T is not @Inherited.

It is a compile-time error if an annotation type interface T 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 interface T specifies a containing annotation type interface of TC, then the value() method of TC has a return type involving T, specifically T[].

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 interface TC may be the containing annotation type interface of some annotation type interface T while also having its own containing annotation type interface TC '. 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 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 repeatable annotation type with annotations of containing annotation type (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.

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.

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

      • Otherwise, the compile-time type of ExpressionName or Primary is the qualifying type of the reference.

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

    The reference to f must be compiled into a symbolic reference to the erasure (4.6) of the qualifying type 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 of the method invocation as follows:

    • If D is Object then the qualifying type 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 be C; otherwise, let T be the innermost lexically enclosing type class or interface declaration of which m is a member. In either case, T is the qualifying type of the method invocation.

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

        • Otherwise, the compile-time type of ExpressionName or Primary is the qualifying type 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 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 of the method invocation; if TypeName denotes an interface X, X is the qualifying type 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 of the invocation, plus the erasure of the 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 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 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 of the expression is the compile-time type of the expression.

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

    • If the expression is of the form this(...), then the qualifying type 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 of the invocation, plus the 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.4 Evolution of Classes

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

The type of the expression is T.

It is a compile-time error if the expression occurs in a class or interface which is not an inner class of class T or T itself.

15.9 Class Instance Creation Expressions

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.12 Method Invocation Expressions

15.12.1 Compile-Time Step 1: Determine Class or Interface 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 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 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.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:

...