The meaning of a name classified as an ExpressionName is determined as follows.
If an expression name consists of a single Identifier, then:
final
(§8.3.1.2), then the expression name denotes the value of the field. The type of the expression name is the declared type of the field. If the Identifier appears in a context that requires a variable and not a value, then a compile-time error occurs.
If the field is an instance variable (§8.3.1.1), the expression name must appear within the declaration of an instance method (§8.4), constructor (§8.6), or instance variable initializer (§8.3.2.2). If it appears within a static
method (§8.4.3.2), static initializer (§8.5), or initializer for a static
variable (§8.3.1.1, §12.4.2), then a compile-time error occurs.
class Test {
static int v;
static final int f = 3;
public static void main(String[] args) { int i; i = 1; v = 2; f = 33; // compile-time error System.out.println(i + " " + v + " " + f); }
}
the names used as the left-hand-sides in the assignments to i
, v
, and f
denote the
local variable i
, the field v
, and the value of f
(not the variable f
, because f
is a
final
variable). The example therefore produces an error at compile time
because the last assignment does not have a variable as its left-hand side. If the
erroneous assignment is removed, the modified code can be compiled and it will
produce the output:
1 2 3
If an expression name is of the form Q.
Id, then Q has already been classified as a
package name, a type name, or an expression name:
static
), then a compile-time error occurs.
final
, then Q.
Id denotes the value of the class variable. The type of the expression Q.
Id is the declared type of the class variable. If Q.
Id appears in a context that requires a variable and not a value, then a compile-time error occurs.
.
Id denotes the class variable. The type of the expression Q.
Id is the declared type of the class variable.
.
Id denotes the value of the field. The type of the expression Q.
Id is the declared type of the field. If Q.
Id appears in a context that requires a variable and not a value, then a compile-time error occurs.
final
field of a class type (which may be either a class variable or an instance variable)
final
field length
of an array type
then Q.
Id denotes the value of the field. The type of the expression Q.
Id is the declared type of the field. If Q.
Id appears in a context that requires a variable and not a value, then a compile-time error occurs.
.
Id denotes a variable, the field Id of class T, which may be either a class variable or an instance variable. The type of the expression Q.
Id is the declared type of the field
class Point { int x, y; static int nPoints; } class Test { public static void main(String[] args) { int i = 0; i.x++; // compile-time error Point p = new Point(); p.nPoints(); // compile-time error } }
encounters two compile-time errors, because the int
variable i
has no members,
and because nPoints
is not a method of class Point
.