Search code examples
javajava-7jls

Java 7 specification: variable identifiers are names, but field names are not? Why?


http://docs.oracle.com/javase/specs/jls/se7/html/jls-6.html#jls-6.2

Specification says:

In determining the meaning of a name (§6.5), the context in which the name appears is taken into account. The rules of §6.5 distinguish among contexts where a name must denote (refer to) a package (§6.5.3), a type (§6.5.5), a variable or value in an expression (§6.5.6), or a method (§6.5.7).

So, as far as I understand, names can only denote the above entities - which do not contain fields.

This seems to be in line with the statements made a bit below:

Not all identifiers in a program are a part of a name. Identifiers are also used in the following situations:

  • ...

  • In field access expressions (§15.11), where an identifier occurs after a "." token to indicate a member of an object that is the value of an expression or the keyword super that appears before the "." token

  • ...

So, my question is: what is the reason for this distinction between local variables and fields?


Solution

  • The important part is:

    The rules of §6.5 distinguish among contexts where a name must denote (refer to) a package (§6.5.3), a type (§6.5.5), a variable or value in an expression (§6.5.6), or a method (§6.5.7).

    A reference to a field is also a name in this context because it is a value in an expression. (§6.5.6)

    There are many points at which this is explained in §6.5.6, I've highlighted a few in bold below:

    6.5.6.1. Simple Expression Names

    If an expression name consists of a single Identifier, then there must be exactly one declaration denoting either a local variable, parameter, or field visible (§6.4.1) at the point at which the Identifier occurs. Otherwise, a compile-time error occurs.

    If the declaration denotes an instance variable (§8.3), the expression name must appear within the declaration of an instance method (§8.4), constructor (§8.8), instance initializer (§8.6), or instance variable initializer (§8.3.2.2).

    [...]

    6.5.6.2. Qualified Expression Names

    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.

    [...]

    If Q is an expression name, let T be the type of the expression Q:

    If T is not a reference type, a compile-time error occurs.

    If there is not exactly one accessible (§6.6) member of the type T that is a field named Id, then a compile-time error occurs.

    [etc. etc.]