(1) 在那个类的构建器中。
(2) 在对象定义的时候。这意味着它们在构建器调用之前肯定能得到初始化。
(3) 紧靠在要求实际使用那个对象之前。这样做可减少不必要的开销——假如对象并不需要创建的话。
源码:
// (1) Constructor initialization with composition
class Soap {
private String s;
Soap() {
System.out.println("Soap()");
s = new String("Constructed");
}
public String toString() {
return s;
}
}
public class Bath {
//(2) Initializing at point of definition
private String s1 = new String("Happy"),
s2 = "Happy", s3, s4;
Soap castile;
int i;
float toy;
Bath() {
System.out.println("Inside Bath()");
s3 = new String("Joy");
i = 47;
toy = 3.14f;
castile = new Soap();
}
void print() {
// (3) Delayed initialization :
if(s4 == null)
s4 = new String("Joy");
prt("s1 = " + s1);
prt("s2 = " + s2);
prt("s3 = " + s3);
prt("s4 = " + s4);
prt("i = " + i);
prt("toy = " + toy);
prt("castile = " + castile);
}
public static void main(String[] args) {
Bath b = new Bath();
b.print();
}
static void prt(String s) {
System.out.println(s);
}
}
运行结果: