你问的是不是初始化模块。初始化模块和构造方法一起用于初始化对象,如果有多个构造方法共享一段代码,并且每个构造方法不会调用其他构造方法,就可以使用初始化模块来简化类,
//e.g.
public class Book{
private static int numOfObjects;
private String title;
private int id;
public Book(String title){
this.title=title;
}
public Book(int id){
this.id=id;
}
{
numOfObjects++;
}
}
等价于
public class Book{
private static int numOfObjects;
private String tltle;
private int id;
public Book(String title){
numOfObjects++;
this.title=title;
}
public Book(int id){
numOfObjects++;
this.id=id;
}
}
|