问题描述
这是一些在尚未初始化的类上调用静态方法A.f()的代码。
有人可以用JLS来解释这段代码的行为吗?
A类{
final static Object b = new B();
final static int S1 = 1;
final static Integer S2 = 2;
static void f(){
System.out.println(S1);
System.out.println(S2);
}
}
B类{
static {
A.f();
}
}
公共类App
{
public static void main(String [] args)
{
Af ();
}
}
输出:
1
null
1
2
af()
in App.main()
触发类的初始化 A
。
初始化所有常量变量。唯一的常量变量是 S1
,现在 1
。
然后,其他静态字段按文本顺序初始化。 b
是第一个字段,它触发类 B
的初始化,后者又调用 Af ()
。 S2
只是 null
因为它尚未初始化。 b
的初始化现已完成。最后但并非最不重要的是, S2
初始化为整数
对象 2
。
S2
不是常量变量,因为它不是原始类型 int
但引用类型 Integer
。 S2 = 2;
是的自动装箱速记,S2 = Integer.valueOf(2);
。
Here is some code that calls static method A.f() on class that is not initialized yet.Can someone explain behavior of this code in terms of JLS?
class A {
final static Object b = new B();
final static int S1 = 1;
final static Integer S2 = 2;
static void f() {
System.out.println(S1);
System.out.println(S2);
}
}
class B {
static {
A.f();
}
}
public class App
{
public static void main( String[] args )
{
A.f();
}
}
Output:
1
null
1
2
A.f()
in App.main()
triggers initialization of class A
.
All constant variables are initialized. The only constant variable is S1
, which now is 1
.
Then, the other static fields are initialized in textual order. b
is the first field, which triggers initialization of class B
, which in turn calls A.f()
. S2
is simply null
because it is not initialized yet. Initialization of b
is now complete. Last but not least, S2
is initialized to the Integer
object 2
.
S2
is not a constant variable because it is not of the primitive type int
but of the reference type Integer
. S2 = 2;
is an auto-boxing shorthand for S2 = Integer.valueOf(2);
.
12.4.2. Detailed Initialization Procedure
4.12.5. Initial Values of Variables
这篇关于最终字段初始化顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!