构造代码块
构造代码块是在类中定义的{}
class Person {
private String description;
private String name;
{
description = "this is a person";
}
public Person(String name) {
name = name;
}
}
构造代码块优先于构造函数执行,用于初始化实例的共性域,而构造函数用于初始化实例的特性域(如上每个人的描述都是一样,但名字不一样)
静态代码块
静态代码块是在类中定义的static{}
class Person {
private static int total;
private int id;
static {
total = 0;
}
public Person() {
this.id = total;
total = total + 1;
}
}
静态代码块优先于构造代码块执行,用于初始化类及其所有实例的静态域,它们共有类中的静态域(如上利用静态域对每个Person实例顺序编号)
块的执行顺序
静态代码块只会执行一次,而构造代码块会在每次创建实例时执行
class Person {
private static int total;
private int id;
private String description;
{
description = "this is a person";
System.out.println("{}");
}
static {
total = 0;
System.out.println("static{}");
}
public Person() {
this.id = total;
total = total + 1;
System.out.println("Person()");
}
}
对于如下调用
Person p1 = new Person();
Person p2 = new Person();
将打印
static{}
{}
Person()
{}
Person()