public class A {
private String name;
private int id;
private static int nextId=1;
static {
System.out.printf("静态初始化块第%d次运行\n", nextId);
}
{
System.out.printf("对象初始化块第%d次运行\n", nextId);
}
public A(String name) {
this.name = name;
this.id = nextId++;
}
public static void main(String[] args) {
A a1 = new A("a1");
System.out.println(a1.id);
A a2 = new A("a2");
System.out.println(a2.id);
}
}
添加static
关键字的块是静态初始化块,只会在类第一次加载的时候运行一次;没有static
关键字的块是对象初始化块,每次调用构造函数的时候都会运行。