toString
每一个非基本类型的对象都有一个toString()方法,当编译器需要一个String时,该对象却没有时,toString方法就会被调用。
1 class WaterSource{ 2 private String s; 3 WaterSource(){ 4 System.out.println("WaterSource()\n"); 5 s = "Constructed"; 6 } 7 public String toString(){ 8 return s; 9 }; 10 11 } 12 public class zuheyufa { 13 14 /** 15 * @param args 16 */ 17 private String value1,value2,value3,value4; 18 private WaterSource source = new WaterSource(); 19 private int i; 20 private float f; 21 public String toString(){ 22 return "value1 =" + value1 + " " + 23 "value2 =" + value2 + " " + 24 "value3 =" + value3 + " " + 25 "value4 =" + value4 +"\n" + 26 "i =" + i + " " + 27 "f =" + f + " " + 28 "source = " + source; 29 } 30 31 public static void main(String[] args) { 32 // TODO Auto-generated method stub 33 zuheyufa zuhe = new zuheyufa(); 34 System.out.println(zuhe); 35 } 36 37 }
结果为:
WaterSource()
value1 =null value2 =null value3 =null value4 =null
i =0 f =0.0 source = Constructed
上例所示,当主函数需要输出zuheyufa的对象时,该对象没有String,因此会调用toString方法。
如果稍稍修改一下WaterSource类,为该类中的构造函数传递一个String参数,那么结果将发生变化了。
1 class WaterSource{ 2 private String s ; 3 WaterSource(String str){ 4 System.out.println("WaterSource()\n"); 5 s = "Constructed"; 6 s = str; 7 } 8 public String toString(){ 9 return s; 10 }; 11 12 } 13 public class zuheyufa { 14 15 /** 16 * @param args 17 */ 18 private String value1,value2,value3,value4; 19 private WaterSource source = new WaterSource("jk"); 20 private int i; 21 private float f; 22 public String toString(){ 23 return "value1 =" + value1 + " " + 24 "value2 =" + value2 + " " + 25 "value3 =" + value3 + " " + 26 "value4 =" + value4 +"\n" + 27 "i =" + i + " " + 28 "f =" + f + " " + 29 "source = " + source; 30 } 31 32 public static void main(String[] args) { 33 // TODO Auto-generated method stub 34 zuheyufa zuhe = new zuheyufa(); 35 System.out.println(zuhe); 36 } 37 38 }
结果为:
WaterSource()
value1 =null value2 =null value3 =null value4 =null
i =0 f =0.0 source = jk