考虑以下代码:-
class Name {
{System.out.println("hi");}
public static void main(String[] args) {
System.out.println(waffle());
}
static boolean waffle() {
try {
return true;
} finally {
return false;
}
}
}
这永远不会输出 "hi"。为什么是这样?
最佳答案
大括号中的代码是instance initializer .
来自 The Java Language Specification, Third Edition , Section 8.6 :
An instance initializer declared in a class is executed when an instance of the class is created (§15.9), as specified in §8.8.5.1.
如果Name
类被执行,public static void main(String[])
方法被Java虚拟机调用,但是Name
class is not is not is not instantiated, 因此实例初始化器中的代码将永远不会被执行。
还有一个static initializer ,它在外观上类似于实例初始化器,但它前面有 static
关键字:
static {
// Executed when a class is first accessed.
}
同样,来自 The Java Language Specification, Third Edition , Section 8.7 :
Any static initializers declared in a class are executed when the class is initialized and, together with any field initializers (§8.3.2) for class variables, may be used to initialize the class variables of the class (§12.4).
Initializing Fields来自 The Java Tutorials 的页面还包含有关静态和实例初始化程序 block 的信息。
关于java - '{}' 中的主类 block 从不执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1351397/