轉載自:http://blog.csdn.net/anddyhua/article/details/42675099 爲什麼toString 方法會自動被調用
先執行下面一段代碼:
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 方法會自動被調用 (百度文庫)
源碼
valueOf public static String valueOf(Object obj) 返回 Object 參數的字符串表示形式。
參數: obj - 一個 Object。 返回: 如果參數爲 null, 則字符串等於 "null";否則, 返回 obj.toString() 的 值
這個問題其實比較簡單的,大家可以直接看 Java 中相關類的源代碼就可以知道了。
現在的問題是,當用戶調用 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()的最終根源。