Java的初始化块


1.类初始化块

// 类初始化块只执行一次
public class A {

static {
System.out.println("Hello World");
}

public static void main(String[] args) {
A a = new A();
A a1 = new A();
A a2 = new A();
}
}

输出:
Hello World

1.实例初始化块

// 实例初始化块每次实例化都会执行一次
public class B {

{
System.out.println("Hello World");
}

public static void main(String[] args) {
B b = new B();
B b1 = new B();
B b2 = new B();
}
}

输出:
Hello World
Hello World
Hello World