每個非基本類的對象都有一個toString()方法,若編輯器本來希望的是一個String,但獲得的卻是某個這樣的對象,就會調用這個方法。如果我們創建一個允許這種行爲的類時,就需要寫一個toString()方法。
//類再生,合成的語法
class Soap{
private String s;
Soap(){
System.out.println("Soap");
s = new String("Constructed");
}
public String toString(){
return s;
}
}
public class Bath {
Soap castille;
Bath(){
System.out.println("Inside Bath()");
castille = new Soap();
}
void print(){
System.out.println("castille = " + castille);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Bath b = new Bath();
b.print();
}
}