问题
for the following code:
class A
{
public static int X;
static { X = B.Y + 1;}
}
public class B
{
public static int Y = A.X + 1;
static {}
public static void main(String[] args) {
System.out.println("X = "+A.X+", Y = "+B.Y);
}
}
the output is: X = 1, Y = 2
Why? and How???
-Ivar
P.S: Code snippet taken from JavaCamp.org
回答1:
Here is what happens in chronological order:
Class
B
contains the main-method so it is loaded by the class loader.Initialization of
B
referencesA
, so classA
is loaded.A
has a static variableX
initialized toB.Y + 1
.The initialization of
B.Y
hasn't been executed yet, soB.Y
evaluates to 0, and thus 1 is assigned toA.X
Now
A
has finished loading, and the initialization ofB.Y
can take place.The value of
A.X + 1
(1 + 1) is assigned toB.Y
.The values of
A.X
andB.Y
are printed as1
and2
respectively.
Further reading:
Java Language Specification, §12.4.1 When Initialization Occurs
回答2:
This is only my guess:
- Class
B
is loaded because it containsmain
which you have requested to be executed. - Class loader discovers that
B
requiresA
to operate (it usesA
by accessing its static field) - Class
B
is loaded. - Class
A
requires classB
which happens to be already loaded, but not yet initialized A
carelessly loadsB.Y
(initialized to 0 by that time by default), since the class looks like loaded (language design flaw?)A.X = 0 + 1
A
is now loaded, class loader can continue to load and initializeB
B.Y = 1 + 1
.
回答3:
B being public starts to load itself.
Sees A.X = B.Y +1 == which is 0 to start with (default int object value) hence 1;
initializes B = 1 + 1 = 2;
hence the answer.
来源:https://stackoverflow.com/questions/6416408/static-circular-dependency-in-java