[英]Unexpected Java Text Output
When I run this code, it outputs blockA blockB blockA
. 当我运行此代码时,它输出blockA blockB blockA
。
I expected the output to be blockB blockA blockA
. 我期望输出为blockB blockA blockA
。
Why is the output blockA blockB blockA
, not blockB blockA blockA
? 为什么输出blockA blockB blockA
而不是blockB blockA blockA
?
public class Test
{
public static Test t1 = new Test();
{
System.out.println("blockA");
}
static
{
System.out.println("blockB");
}
public static void main(String[] args)
{
Test t2 = new Test();
}
}
Here In class, you have put following statement first. 在课堂上,您首先添加了以下语句。
public static Test t1 = new Test();
So it will be execute class initializer 因此它将是执行类的初始值设定项
{
System.out.println("blockA");
}
So blockA will be printed. 因此,将打印blockA 。
Then static initializer is executed 然后执行静态初始化程序
static
{
System.out.println("blockB");
}
and blockB is printed 并打印出blockB
finally code inside main function is executed 最后执行主函数中的代码
Test t2 = new Test();
and that will trigger class initializer again 这将再次触发类初始化器
{
System.out.println("blockA");
}
and so blockA is printed again. 因此再次打印blockA 。
A detailed description about execution order about class and static initializer is here jls-12.4.2 有关类和静态初始化程序的执行顺序的详细说明,请参见jls-12.4.2。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.