toString(),每一个非基本类型的对象都有一个toString()方法,当编译器需要一个Sting,而你只有一个对象时,该方法会自动调用。
class WaterSource { private String s; WaterSource(){ System.out.println("WaterSource()"); s = "Constructed"; } public String toString(){return s;} } public class FuYong01{ private String valve1,valve2,valve3,valve4; private WaterSource source = new WaterSource(); private int i; private float f; public String toString(){ return "valve1 = " + valve1 + " " + "valve2 = " + valve2 + " " + "valve3 = " + valve3 + " " + "valve4 = " + valve4 + " " + "1 = " + i + " " + "f = " + f + " " + "source = " + source; //自动调用toSting方法 } public static void main2(String[] args){ FuYong01 fy = new FuYong01(); System.out.println(fy); //就相当于System.out.println(fy.toSting()); } }
运行结果:
WaterSource()
valve1 = null valve2 = null valve3 = null valve4 = null
1 = 0 f = 0.0 source = Constructed
注意:
域中为基本类型是能够被初始化为0,但是对象引用会被初始化为null;看上边输出结果的红色null,就是因为引用的对象。
每一个类中都重写了一个toSting方法;我还以为同一个文件中只能有一个toSring方法了