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.
b的初始化是否发生在类加载上?
初始化c的问题相同
首先b或c的初始化会发生什么?如果存在,请给我一个关于这个问题的java文档的参考。
Thanks
2 个解决方案
#1
2
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.
类变量在类加载时以文本顺序初始化,就好像它们是单个块一样,因此b首先初始化然后是c,如Java语言规范中定义的详细初始化过程的步骤9中所述。
#2
0
The code block with the static modifier signifies a class initializer; without the static modifier the code block is an instance initializer.
带有static修饰符的代码块表示类初始值设定项;如果没有静态修饰符,则代码块是实例初始值设定项。
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.
实例初始化程序在实例化时定义的顺序执行,紧接在执行构造函数代码之前,在超级构造函数的调用之后立即执行。
#1
2
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.
类变量在类加载时以文本顺序初始化,就好像它们是单个块一样,因此b首先初始化然后是c,如Java语言规范中定义的详细初始化过程的步骤9中所述。
#2
0
The code block with the static modifier signifies a class initializer; without the static modifier the code block is an instance initializer.
带有static修饰符的代码块表示类初始值设定项;如果没有静态修饰符,则代码块是实例初始值设定项。
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.
实例初始化程序在实例化时定义的顺序执行,紧接在执行构造函数代码之前,在超级构造函数的调用之后立即执行。