在Java中使用花括号的奇怪行为 [英] Strange behavior using braces in Java
本文介绍了在Java中使用花括号的奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我运行以下代码时:
public class Test {
Test(){
System.out.println("1");
}
{
System.out.println("2");
}
static {
System.out.println("3");
}
public static void main(String args[]) {
new Test();
}
}
我希望按以下顺序获得输出: / p>
I expect to get the output in this order:
1
2
3
但是我得到的却是相反的顺序:
but what I got is in reverse order:
3
2
1
有人可以解释为什么输出顺序相反吗?
Can anyone explain why it is output in reverse order?
===============
================
此外,当我创建多个 Test
的一个实例:
Also, when I create more than one instance of Test
:
new Test();
new Test();
new Test();
new Test();
静态块仅在第一时间执行。
推荐答案
这完全取决于初始化语句的执行顺序。您的测试表明该顺序为:
It all depends on the order of execution of initialization statements. Your test demonstrates that this order is:
- 静态初始化块
- 实例初始化块
- 构造函数
编辑
感谢您的评论,现在我可以引用JVM规范中的相应部分。 在这里,详细的初始化过程。
Thanks for the comments, now I can quote the appropriate part in the JVM specification. Here it is, the detailed initialization procedure.
这篇关于在Java中使用花括号的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文