Class variables are initialized at class load time, in textual order, as though they were a single block, so b is initialized first then c, as noted in step 9 of the Detailed Initialization Procedure defined in the Java Language Specification.
When does Static field inline initialization occur
-
18-10-2022 - |
Pregunta
Consider this:
Class A
{
private static B b = new B();
private static C c;
static
{
c= new C();
}
}
- Is the initialization of
b
occur on class load? - Same question for initialization of
c
- What happends first initalization of
b
orc
?
Please give me a reference for java docs regarding this issues if exists.
Thanks
Solución
Otros consejos
The code block with the static modifier signifies a class initializer; without the static modifier the code block is an instance initializer.
Static initializers are executed in the order they are defined (top down, just like simple variable initializers) when the class is loaded (actually, when it's resolved, but that's a technicality).
Instance initializers are executed in the order defined when the class is instantiated, immediately before the constructor code is executed, immediately after the invocation of the super constructor.
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow