2016-10-04 129 views
-1

为什么输出? :球体0为什么这个Java代码隐式调用toString()方法?

不知何故,它隐式地调用toString()方法?这个怎么用 ?

class BerylliumSphere { 
    private static long counter = 0; 
    private final long id = counter++; 
    public String toString() { 
     return "Sphere " + id; 
    } 
} 

public class Test { 
    public static void main (String[] args) { 
     BerylliumSphere spheres = new BerylliumSphere(); 
     System.out.println(spheres); 
    } 
} 

// output: Sphere 0 
+0

有没有神奇的,它不是,做它的“Java”,但'println'方法。你可以自己实现这样的方法。 http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/java/io/PrintStream.java#820 –

+1

在println()中传递对象总是给出toString表示 – Kahn

+1

这不是“隐含的”,它是“明确的”,只是看看'println'的作用。 – Tom

回答

3

System.outPrintStream实例,它是System的静态成员。 PrintStream类有一个函数println(),它接受类型为Object的参数。这个功能,在打开JDK,如下所示:

public void println(Object x) { 
    String s = String.valueOf(x); 
    synchronized (this) { 
     print(s); 
     newLine(); 
    } 
} 

如果你看String.valueOf(),它接受Object类型的参数,可以看到:

public static String valueOf(Object obj) { 
    return (obj == null) ? "null" : obj.toString(); 
} 

有没有神奇。它只是一个Java类,在对象上调用toString

进一步阅读

+0

但我不明白为什么它使用我在BerylliumSphere类中编写的toString()方法,因为我从来没有调用它? –

+1

您需要了解我的朋友多态性!通过创建你自己的toString(),你已经覆盖了所有超类中相同函数的实现。 – christopher

1

当您尝试System.out.println(spheres)它看起来像如下:

public void println(Object x) { 
     String s = String.valueOf(x); 
     synchronized (this) { 
      print(s); 
      newLine(); 
     } 
    } 

这是valueOf(Object obj)方法:

public static String valueOf(Object obj) { 
     return (obj == null) ? "null" : obj.toString(); 
    } 
2

这里是System.out.println做:https://docs.oracle.com/javase/7/docs/api/java/io/PrintStream.html#println%28java.lang.Object%29

它说如下:

此方法调用在第一将String.valueOf(x)用于获得所述印刷 对象的字符串值,然后行为就像先调用打印(字符串) 然后调用println()。

这里是什么String.valueOf做:https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#valueOf%28java.lang.Object%29

它说:

如果参数为null,则等于 “零” 的字符串;否则,返回obj.toString()的值 。

简而言之,打印对象将导致调用其toString方法并打印返回的内容。

+0

但是我不明白为什么它使用我在BerylliumSphere类中编写的toString()方法,因为我从来没有调用它? –

相关问题