代码示例:
public class Test {
public static void main(String[] args) {
new Construct();
new Construct("小明", 18);
}
}
class Construct {
public String name;
public int age;
public Construct(){
System.out.println("Construct:无参构造");
}
public Construct(String name, int age) {
this.name = name;
this.age = age;
System.out.println("Construct:有参构造" + "name:" + name + ",age:" + age);
}
static {
System.out.println("静态代码块!!!");
}
{
System.out.println("构造代码块!!!");
}
}
执行结果:
Connected to the target VM, address: '127.0.0.1:55491', transport: 'socket'
静态代码块!!!
构造代码块!!!
Construct:无参构造
构造代码块!!!
Construct:有参构造name:小明,age:18
Disconnected from the target VM, address: '127.0.0.1:55491', transport: 'socket'
Process finished with exit code 0
总结:
代码块区分:静态代码块(有static关键字修饰)、构造代码块(无static关键词修饰)
是否允许多次执行:静态代码块只在类加载的时候执行一次,构造代码块每次类实例化时均会执行一次,且在构造方法前执行;
执行优先级:静态代码块 > 构造代码块 > 构造方法