Java Reference
In-Depth Information
This program compiles without error; it initializes
j
to
1
when class
Test
is initialized,
and initializes
f
to the current value of
j
every time an instance of class
Test
is created.
Initialization expressions for instance variables are permitted to refer to the current object
Use of instance variables whose declarations appear textually after the use is some-
times restricted, even though these instance variables are in scope. See §
8.3.2.3
for
the precise rules governing forward reference to instance variables.
8.3.2.3. Restrictions on the use of Fields during Initialization
The declaration of a member needs to appear textually before it is used only if the member
is an instance (respectively
static
) field of a class or interface
C
and all of the following con-
ditions hold:
• The usage occurs in an instance (respectively
static
) variable initializer of
C
or in an
instance (respectively
static
) initializer of
C
.
• The usage is not on the left hand side of an assignment.
• The usage is via a simple name.
•
C
is the innermost class or interface enclosing the usage.
It is a compile-time error if any of the four requirements above are not met.
Example 8.3.2.3-1. Restrictions on Field Initialization
A compile-time error occurs for this program:
class Test1 {
int i = j; // compile-time error:
// incorrect forward reference
int j = 1;
}
whereas the following program compiles without error:
class Test2 {
Test2() { k = 2; }
int j = 1;
int i = j;
int k;
}