每个非基本类的对象都有一个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();
}
}