2015-04-24 180 views
-4
class Frog 
{ 
    private int id; 
    private String name; 
    public Frog(int id,String name) 
    { 
     this.id=id; 
     this.name=name; 
    } 
    public String toString(){ 
     return id+" "+name; 
    } 
} 

public class Verify 
{ 
    public static void main(String[] args) 
    { 
     Frog frog1=new Frog(4,"maggie"); 
     System.out.println(frog1); 
    } 
} 

在上面的代碼中,我們得到了在傳遞「frog1」和「frog1.toString」到println方法,爲什麼同樣的結果?請任何人解釋我。在第一種情況下,我們沒有明確調用toString方法。爲什麼這個java程序是給予相同的輸出

+5

這段代碼是否編譯? – Reimeus

+1

['PrintWriter.println(Object)'](http://docs.oracle.com/javase/8/docs/api/java/io/PrintWriter.html#println-java.lang.Object-)是做什麼的?你如何看待它得到一個任意'Object'的String表示? –

+0

此外,請遵守Java命名約定,類應該在'PascalCase'中,'camelCase'是爲變量保留的。偏離這不僅會讓你的代碼更難閱讀,而且還會混淆自動語法突出顯示。 –

回答

2

因爲println(Object)調用intern的String.valueOf方法,其中 最後調用給定Object的toString方法。

見的PrintStream和字符串的文件:

https://docs.oracle.com/javase/7/docs/api/java/io/PrintStream.html#println(java.lang.Object)

http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#valueOf(java.lang.Object)

這裏是的println(對象)的實現方法: http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/io/PrintStream.java

786 
787  public void println(Object x) { 
788   String s = String.valueOf(x); 
789   synchronized (this) { 
790    print(s); 
791    newLine(); 
792   } 
793  } 

這裏是執行valueOf方法: http://developer.classpath.org/doc/java/lang/String-source.html

/** 
1629: * Returns a String representation of an Object. This is "null" if the 
1630: * object is null, otherwise it is <code>obj.toString()</code> (which 
1631: * can be null). 
1632: * 
1633: * @param obj the Object 
1634: * @return the string conversion of obj 
1635: */ 
1636: public static String valueOf(Object obj) 
1637: { 
1638:  return obj == null ? "null" : obj.toString(); 
1639: } 
相關問題