Java Reference
In-Depth Information
the expression
s.z()
refers to the
z
method of class
T
, despite the fact that the type of
the expression
s
is
S
. Method
z
of class
T
overrides method
z
of class
S
.
Example 15.11.1-2. Receiver Variable Is Irrelevant For
static
Field Access
The following program demonstrates that a null reference may be used to access a
class (
static
) variable without causing an exception:
class Test3 {
static String mountain = "Chocorua";
static Test3 favorite(){
System.out.print("Mount ");
return null;
}
public static void main(String[] args) {
System.out.println(favorite().mountain);
}
}
It compiles, executes, and prints:
Mount Chocorua
Even though the result of
favorite()
is
null
, a
NullPointerException
is not thrown. That
“
Mount
” is printed demonstrates that the
Primary
expression is indeed fully evaluated
at run time, despite the fact that only its type, not its value, is used to determine which
field to access (because the field
mountain
is
static
).
15.11.2. Accessing Superclass Members using
super
The form
super.
Identifier
refers to the field named
Identifier
of the current object, but with
the current object viewed as an instance of the superclass of the current class.
The form
T
.super.
Identifier
refers to the field named
Identifier
of the lexically enclosing in-
stance corresponding to
T
, but with that instance viewed as an instance of the superclass of
T
.
The forms using the keyword
super
are valid only in an instance method, instance initializer,
or constructor, or in the initializer of an instance variable of a class. If they appear anywhere
else, a compile-time error occurs.