Java编译器并不是简单的为每个引用都创建一个默认对象,如果想初始化这些引用可以在代码中的下列位置进行:
1.在定义对象得地方,这意味着他们总是能够被构造器调用之前被初始化。
2.在类的构造器中。
3.就在正要使用这些对象之前,这种方式称为惰性初始化,在生成对象不值得级不必每次生成对象的情况下,减少额外的负担。
4.使用实例初始化。
class Soap {
private String s;
Soap() {
System.out.println("Soap()");
s = "Constructed";
}
@Override
public String toString() {
return s;
}
}
public class Bath {
private String
s1 = "Happy", // 定义初始化
s2 = "Happy",
s3, s4;
private Soap castile;
private int i;
private float toy;
public Bath() {
System.out.println("Inside Bath()");
s3 = "Joy";
toy = 3.14f;
castile = new Soap(); // 在类的构造器中被初始化
}
{
i = 47; // 实例初始化
}
@Override
public String toString() {
if (s4 == null)
s4 = "Joy"; // 惰性初始化
return "s1 = " + s1 + "\n" +
"s2 = " + s2 + "\n" +
"s3 = " + s3 + "\n" +
"s4 = " + s4 + "\n" +
"i = " + i + "\n" +
"toy = " + toy + "\n" +
"castile = " + castile;
}
public static void main(String[] args) {
Bath b = new Bath();
System.out.println(b);
}
} /* Output:
Inside Bath()
Soap()
s1 = Happy
s2 = Happy
s3 = Joy
s4 = Joy
i = 47
toy = 3.14
castile = Constructed
*///~