1. 程式人生 > 實用技巧 >Object.toString()詳解

Object.toString()詳解

Object.toString()方法詳解

Object類是所有類的父類,位於java.lang包中,是所有類的根。

toString()是其中一個常用方法,也是在開發中經常使用的一個方法。

平時我們如果在控制檯直接列印輸出一個物件的例項時,其實呼叫的就是Object類的toString()方法。

類可以實現toString方法,在控制檯中列印一個物件會自動呼叫物件類的toString方法,所以我們可以實現自己的toString方法在控制檯中顯示關於類的有用資訊。

Date now = new Date();
System.out.println("now = " + now);//相當於下一行程式碼
System.out.println("now = " + now.toString());

在java中任何物件都會繼承Object物件,所以一般來說任何物件都可以呼叫toString這個方法。這是採用該種方法時,常派生類會覆蓋Object裡的toString()方法。

但是在使用該方法時必須要注意,必須要保證Object不能是null值,否則將丟擲NullPointerException異常。

JDK原始碼:

 1     /**
 2      * Returns a string representation of the object. In general, the
 3      * {
@code toString} method returns a string that 4 * "textually represents" this object. The result should 5 * be a concise but informative representation that is easy for a 6 * person to read. 7 * It is recommended that all subclasses override this method. 8 * <p> 9
* The {@code toString} method for class {@code Object} 10 * returns a string consisting of the name of the class of which the 11 * object is an instance, the at-sign character `{@code @}', and 12 * the unsigned hexadecimal representation of the hash code of the 13 * object. In other words, this method returns a string equal to the 14 * value of: 15 * <blockquote> 16 * <pre> 17 * getClass().getName() + '@' + Integer.toHexString(hashCode()) 18 * </pre></blockquote> 19 * 20 * @return a string representation of the object. 21 */ 22 public String toString() { 23 return getClass().getName() + "@" + Integer.toHexString(hashCode()); 24 }

在進行String類與其他型別的連線操作時,自動呼叫toString()方法

當我們列印一個物件的引用時,實際是預設呼叫這個物件的toString()方法

當列印的物件所在類沒有重寫Object中的toString()方法時,預設呼叫的是Object類中toString()方法。

當我們列印物件所 在類重寫了toString(),呼叫的就是已經重寫了的toString()方法,一般重寫是將類物件的屬性資訊返回。