合成只需在新類別中放入物件參考。非基本型別放參考,基本型別直接定義。toString() 讓物件能自動轉為字串配合列印。
//: SprinklerSystem.java
class WaterSource {
private String s;
WaterSource() { System.out.println("WaterSource()"); s="Constructed"; }
public String toString() { return s; }
}
public class SprinklerSystem {
private String valve1, valve2, valve3, valve4;
WaterSource source; int i; float f;
void print() {
System.out.println("valve1 = "+valve1);
System.out.println("source = "+source); // 自動呼叫 toString()
}
public static void main(String[] args) {
SprinklerSystem x = new SprinklerSystem(); x.print();
}
} ///:~
輸出顯示:基本型別自動初始化為 0/false,物件參考預設為 null。編譯器不會自動為參考建立物件,避免不必要開銷。
//: Bath.java
class Soap {
private String s;
Soap() { System.out.println("Soap()"); s="Constructed"; }
public String toString() { return s; }
}
public class Bath {
private String s1="Happy", s2="Happy", s3, s4;
Soap castille; int i; float toy;
Bath() {
System.out.println("Inside Bath()");
s3="Joy"; i=47; toy=3.14f; castille=new Soap();
}
void print() {
if(s4==null) s4="Joy"; // 延遲初始化
System.out.println("s1="+s1+"\ns2="+s2+"\ns3="+s3+"\ns4="+s4);
System.out.println("i="+i+" toy="+toy+" castille="+castille);
}
public static void main(String[] args) { Bath b=new Bath(); b.print(); }
} ///:~
輸出順序證明:Inside Bath() → Soap() → 列印各欄位
三種策略:(1) 定義處初始化 (2) 建構子中初始化 (3) 使用前延遲初始化(減少開銷)。