Java 类中toString 及类的组合

class WaterSource{
	private String s;
	WaterSource(){
		System.out.println("WaterSource()");
		s="Contructed";
	}
	public String toString(){return s;}
}
public class SprinklerSystem {
private String value1,value2,value3,value4;
private WaterSource source=new WaterSource();
private int i;
private float f;
public String toString(){
	return 
	           "value1 = "+value1+" "+
	           "value2 = "+value2+" "+
	           "value3 = "+value3+" "+
	           "value4 = "+value4+"\n "+
	           "i = "+i+" "+"f = "+f+" "+
	           "source = "+source;
}
public static void main(String[] args){
	SprinklerSystem sprinker=new SprinklerSystem();
	System.out.println(sprinker);
}
}
/*
 * 在上面两个类所定义的方法中,有一个很特殊:toString().每个非基本类型的对象都有一个toString()方法,而且当编译器
 * 需要一个String而你只有一个对象时,该方法就会被调用。
 */

输出:

WaterSource()
value1 = null value2 = null value3 = null value4 = null
 i = 0 f = 0.0 source = Contructed


猜你喜欢

转载自blog.csdn.net/u014112584/article/details/42739915