public class InitializerIndex {
public InitializerIndex() {
// TODO Auto-generated constructor stub
System.out.println("Default Constructor");
}
static {
System.out.println("Static Block one");
}
{
System.out.println("Init one");
}
void letsRoll() {
}
public static void main(String[] args) {
new InitializerIndex().letsRoll();
new InitializerIndex().letsRoll();
}
{
System.out.println("Init Two");
}
static {
System.out.println("Static Block two");
}
}
将有以下输出:
Static Block one
Static Block two
Init one
Init Two
Default Constructor
Init one
Init Two
Default Constructor
首先加载所有静态内容,然后加载实例内容 . 静态内容仅加载一次 .
Even when two objects are created, the static block is called only when the first object is created .
此外,在对象创建时或在构造函数中,如果要使用这样的方法
int var = getVal();
你应该使用静态方法 .