toString
toStirng()方法会返回一个“以文本方式表示”此对象的字符串。结果应是一个简明但易于读懂的信息表达式。建议所有子类都重写此方法
每一个非基本类型的对象都有一个toString()方法,而且当编译器需要一个String而你却只有一个对象时,该方法便会被调用
package object; //: reusing/SprinklerSystem.java // commposition for code reuse class WaterSource { private String s; WaterSource() { System.out.println("WaterSource()"); s = "Constructed"; } public String toString(){return s;} } public class SprinklerSystem{ private String valve1, valve2, valve3, valve4; private WaterSource source = new WaterSource(); private int i; private float f; public String toString(){ return "value1 = " + valve1 + " "+ "value2 = " + valve2 + " "+ "value3 = " + valve3 + " "+ "value4 = " + valve4 + "\n"+ "i = " + i + " " + "f = " + f + " " + "source = " + source; //在这里编译器知道你要将一个String对象("source =") //同WaterSource相加 } public static void main(String[] args) { SprinklerSystem sprinklers = new SprinklerSystem(); System.out.println(sprinklers);//当只有一个对象时会自动调用toString() } }/* output:
WaterSource()
value1 = null value2 = null value3 = null value4 = null
i = 0 f = 0.0 source = Constructed
*///~