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()方法,一般重寫是將類對象的屬性信息返回。