在學Java的過程中用的最多的語句恐怕要數System.out.println();這句話了,經常用這句話類比很多事情,那麼這句話是怎樣實現的呢?
首先,System是位於java.lang包中的一個核心類,如果你查看它的定義,你會發現有這樣一行:
public static final PrintStream out;
接著在進一步,點擊PrintStream這個超連結,在METHOD頁面,你會看到大量定義的方法,尋找println,會有這樣一行:
public void println(Object o)
Object並不是一個字串,它列印的到底是什麼呢,看下面這句話:
Prints an object. The string produced by theString.valueOf(Object) method is translated into bytes according to the platform's
default character encoding, and these bytes are written in exactly the manner of thewrite(int) method.
它的意思是它將調用String.valueOf(Object)來擷取對象的字串形式。那麼String.valueOf(Object)又是怎麼處理Object對象的呢,JDK協助文檔的解釋如下:
If the argument isnull, then a string equal to
"null"; otherwise, the value ofobj.toString() is returned .
即,如果不為空白,它將調用對象的toString()方法。
好了,現在你應該明白為什麼我們要那樣調用了,out是System的一個靜態變數,所以可以直接使用,而out所屬的類有一個println方法。
而最終要列印的字串則是在類中toString方法所定義的。
附:PrintStream類的繼承關係
Class PrintStream
- java.lang.Object
-
- java.io.OutputStream
-
- java.io.FilterOutputStream
-