合成的定义:在新类里简单地创建原有类的对象。我们把这种方法叫作“合成” 。
一下通过一段程序来说明合成的语法:
package c06;
class Soap{
private String s;
Soap(){
System.out.println("Soap()");
s = new String("Constructed");
}
public String toString(){return s;}
}
public class Bath {
private String s1 = new String("Happy"), s2 = "Happy", s3, s4;
Soap castille;
int i;
float toy;
Bath(){
System.out.println("Inside Bath()");
s3 = new String("Joy");
i = 47;
toy = 3.14f;
castille = new Soap();
}
void print(){
if(s4 == null)
s4 = new String("Joy");
System.out.println("s1=" + s1);
System.out.println("s2=" + s2);
System.out.println("s3=" + s3);
System.out.println("s4=" + s4);
System.out.println("i=" + i);
System.out.println("castille=" + castille);
}
public static void main(String args[]){
Bath b = new Bath();
b.print();
}
}
程序的结果为:
Inside Bath()
Soap()
s1=Happy
s2=Happy
s3=Joy
s4=Joy
i=47
castille=Constructed
大家不久就会知道,每种非基本类型的对象都有一个 toString()方法。若编译器本来希望一个 String,但却获得某个这样的对象,就会调用这个方法。所以在下面这个表达式中:System.out.println("source = " + source) ;
编译器会发现我们试图向一个 WaterSource 添加一个 String 对象( "source =")。这对它来说是不可接受
的,因为我们只能将一个字串“添加”到另一个字串,所以它会说:“我要调用 toString(),把 source 转
换成字串!”经这样处理后,它就能编译两个字串,并将结果字串传递给一个System.out.println()。每次
随同自己创建的一个类允许这种行为的时候,都只需要写一个 toString()方法 。