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
A circular or cyclic dependency is a situation where two or more independent modules or components rely on each other to function properly. This is referred to as mutual recursion. Circular dependency generally occurs in a modular framework while defining a dependency between modules or components.
Avoiding circular dependencies by refactoring The NestJS documentation advises that circular dependencies be avoided where possible. Circular dependencies create tight couplings between the classes or modules involved, which means both classes or modules have to be recompiled every time either of them is changed.
The Mediator Pattern can also help to lift circular dependencies by encapsulating the bidirectional interaction of two or more objects. The downside of your current code is (besides the circular dependency), that whenever class A changes and also data persistence changes, you have to touch and modify class B.
Here is what happens in chronological order:
Class B
contains the main-method so it is loaded by the class loader.
Initialization of B
references A
, so class A
is loaded.
A
has a static variable X
initialized to B.Y + 1
.
The initialization of B.Y
hasn't been executed yet, so B.Y
evaluates to 0, and thus 1 is assigned to A.X
Now A
has finished loading, and the initialization of B.Y
can take place.
The value of A.X + 1
(1 + 1) is assigned to B.Y
.
The values of A.X
and B.Y
are printed as 1
and 2
respectively.
Java Language Specification, §12.4.1 When Initialization Occurs
This is only my guess:
B
is loaded because it contains main
which you have requested to be executed.B
requires A
to operate (it uses A
by accessing its static field)B
is loaded.A
requires class B
which happens to be already loaded, but not yet initializedA
carelessly loads B.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 initialize B
B.Y = 1 + 1
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With