类再生是说对一段代码的使用率高的画,可以在新类里简单的创建原有类的对象。
每种非基本类型的对象都有一个 toString ()方法。若编译器本来希望一个String 但却获得某个这个的对象,就是调用下面的这个方法
System.out.println ( " source = " + source );
编译器并不只是为每个语句创建一个默认对象,因为那样会在许多情况下招致不必要的开销。如果需要某些语句初始化,可以在下面这些地方进行:
1) 在对象定义的时候。这意味着它们在构建器调用之前肯定能得到初始化。
2) 在那个类的构建器中。
3) 紧靠在要求世纪使用那个对象之前,这样可以减少不必要的开销。
/: Bath.java // Constructor initialization with composition class Soap { private String s; Soap() { System.out.println("Soap()"); s = new String("Constructed"); } public String toString() { return s; } } public class Bath { private String // Initializing at point of definition: 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() { // Delayed initialization: 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("toy = " + toy); System.out.println("castille = " + castille); } public static void main(String[] args) { Bath b = new Bath(); b.print(); } }请注意在Bath构建器中,在所有初始化开始之前执行了一个语句。如果不在定义时进行初始化,仍然不能保证能在将一条消息发给一个对象句柄之前会执行任何初始化——除非出现不可避免的运行期违例。
下面是该程序的输出:
调用print()时,它会填充s4,使所有字段在使用之前都获得正确的初始化。Inside Bath() Soap() s1 = Happy s2 = Happy s3 = Joy s4 = Joy i = 47 toy = 3.14 castille = Constructed