Java Reference
In-Depth Information
♦ If the field is a non-blank
final
field, then the result is the value of the specified
class variable in the class or interface that is the type of the
Primary
expres-
sion.
♦ If the field is not
final
, or is a blank
final
and the field access occurs in a con-
structor, then the result is a variable, namely, the specified class variable in the
class that is the type of the
Primary
expression.
• If the field is not
static
:
♦ The
Primary
expression is evaluated. If evaluation of the
Primary
expression
completes abruptly, the field access expression completes abruptly for the
same reason.
♦ If the value of the
Primary
is
null
, then a
NullPointerException
is thrown.
♦ If the field is a non-blank
final
, then the result is the value of the named mem-
ber field in type
T
found in the object referenced by the value of the
Primary
.
♦ If the field is not
final
, or is a blank
final
and the field access occurs in a con-
structor, then the result is a variable, namely the named member field in type
T
found in the object referenced by the value of the
Primary
.
Note that only the type of the
Primary
expression, not the class of the actual object referred
to at run time, is used in determining which field to use.
Example 15.11.1-1. Static Binding for Field Access
class S { int x = 0; }
class T extends S { int x = 1; }
class Test1 {
public static void main(String[] args) {
T t = new T();
System.out.println("t.x=" + t.x + when("t", t));
S s = new S();
System.out.println("s.x=" + s.x + when("s", s));
s = t;
System.out.println("s.x=" + s.x + when("s", s));
}
static String when(String name, Object t) {
return " when " + name + " holds a "
+ t.getClass() + " at run time.";
}
}