Java記錄 -22- Java的基類Object詳解
Java的基類Object詳解Java的JDK文檔要經常查閱使用,最好查看英文的文檔。Oracle官方線上 Java API Specificationshttp://www.oracle.com/technetwork/java/api-141528.html java.lang.Object 類,java.lang包在使用的時候無需顯示匯入,編譯時間由編譯器自動協助我們匯入。API(Application Programinga Interface),應用編程介面。Object obj = new Object();System.out.println(obj);System.out.println(obj.toString());上面列印的兩個內容一樣。當列印引用時,實際上會列印出引用所指向對象的 toString()方法的傳回值,因為每個類都直接或間接的繼承自Object,而Object類中定義了 toString(),因此每個類都有 toString()這個方法。String str = "aaa";System.out.println(str);System.out.println(str.toString());兩個輸出內容都為 aaa,按照上面的理解,Sting一定重寫了Object的 toString()方法。當列印一個引用對象時,會顯樣本如:java.lang.Object@c17164。為什麼會列印這麼一個串呢?我們通過查看Object類的toString()方法就可以知道。 public String toString()Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of: getClass().getName() + '@' + Integer.toHexString(hashCode()) Returns: a string representation of the object.java.lang.Object@c17164 類名+@+地址的十六進位表示形式6. 關於進位的表示,16進位,逢16進一,16進位的數字包括:0~9,A,B,C,D,E,F