toString方法自动调用

当我们使用System.out.println() 打印一个对象时会自动调用toString方法,如下

package com.xinye.bcsx.chapter7;

public class Demo71 {
	public static void main(String[]args){
		Bath b = new Bath();
		System.out.println(b);
	}
}
class Soap{
	private String s;
	Soap(){
		System.out.print("Soap()");
		s = "Constructed";
	}
	public String toString(){
		return s;
	}
}
class Bath{
	private String s1 = "xiao", s2 = "xiao", s3,s4;
	private Soap castille;
	private int i;
	private float toy;
	public Bath(){
		System.out.println("Inside Bath()");
		s3 = "joy";
		toy = 3.14f;
		castille = new Soap();
	}
	public String toString(){
		if(s4 == null)
			s4 = "joy";
		return "s1 = " + s1 + "\n" +
				"s2 = " + s2 + "\n" +
				"s3 = " + s3 + "\n" +
				"s4 = " + s4 + "\n" +
				"i = " + i + "\n" +
				"toy = " + toy + "\n" +
				"castille = " + castille;
	}
}


版权声明:本文为qq_38335112原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。