A static field cannot be referenced before it is defined or initialized:
static Integer j = i; /* compile error */
static final Integer i = 5;
However, when it is referenced from an instance initialization block (in an anonymous inner class), not even a warning is generated.
See example:
class StaticInitialization {
static final Object o = new Object() {{
j = i;
}};
static Integer j, k;
static final Integer i = 5;
static final Object o2 = new Object() {{
k = i;
}};
}
The result is: j == null
, k == 5
, so clearly we've made a reference, order matters, and no warning or compilation error.
Is this code legal?