欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > > 文章正文

为什么toString 方法会自动被调用,toString方法调用

来源: javaer 分享于  点击 38489 次 点评:59

为什么toString 方法会自动被调用,toString方法调用


先看下来自mindview的一段代码:

package reusing;

//: reusing/Bath.java
// Constructor initialization with composition.
import static net.mindview.util.Print.*;

class Soap {
	private String s;

	Soap() {
		print("Soap()");
		s = "Constructed";
	}

	public String toString() {
		return s;
	}
}

public class Bath {
	private String // Initializing at point of definition:
			s1 = "Happy",
			s2 = "Happy", s3, s4;
	private Soap castille;
	private int i;
	private float toy;

	public Bath() {
		print("Inside Bath()");
		s3 = "Joy";
		toy = 3.14f;
		castille = new Soap();
	}

	// Instance initialization:
	{
		i = 47;
	}

	public String toString() {
		if (s4 == null) // Delayed initialization:
			s4 = "Joy";
		return "s1 = " + s1 + "\n" + "s2 = " + s2 + "\n" + "s3 = " + s3 + "\n"
				+ "s4 = " + s4 + "\n" + "i = " + i + "\n" + "toy = " + toy
				+ "\n" + "castille = " + castille;
	}

	public static void main(String[] args) {
		Bath b = new Bath();
		print(b);
	}
}
打印对象b的时候,构造函数内的自动会调用初始化,还自动调用了toString()


为什么toString 方法会自动被调用?这个问题其实比较简单的,大家可以直接看 Java 中相关类的源代码就可以知道了。public static String valueOf(Object obj) 方法
参数: obj 
返回:        如果参数为 null, 则字符串等于 "null";       否则, 返回 obj.toString() 的值
现在的问题是,当用户调用 print 或 println 方法打印一个对象时,为什么会打印出对象的 toString()方法的返回信息。public String toString() { return getClass().getName() + "@" + Integer.toHexString(hashCode()); }1.这个是 Ojbect 中的 toString()方法,toString ()方法会打印出 return 信息。
  public void println(Object x){
             String s = String.valueOf(x);
             synchronized (this) { 
                      print(s); newLine();
      }
   public void print(Object obj) {
              write(String.valueOf(obj));
  }
2.这两个方法是 System.out.print 和 println()方法传入一个 Object 类对象时打印 的内容,当然,传入其它类时,同样如此。 
3.我们看到,在 2 中,当要打印一个对象时,会自动调用 String.valueOf()这个 方法,下面是这个方法的代码: 
public static String valueOf(Object obj) { 
       return (obj == null) ? "null" : obj.toString(); 
}
这个方法中,当传入的对象为 null 时返回一个 null,当非 null 时,则返回这个 obj 的 toString()。
所以, 这就是当我们调用 print 或者 println 打印一个对象时,它会打印出这个 对象的 toString()的最终根源。


相关文章

    暂无相关文章

用户点评