为什么输出? :球体0
不知怎的,它隐式调用了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 :(得分:3)
System.out
是PrintStream
个实例,是System
的静态成员。 PrintStream
类有一个函数println()
,它接受Object
类型的参数。 Open 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();
}
没有魔力。它只是一个在对象上调用toString
的Java类。
进一步阅读
答案 1 :(得分:2)
以下是System.out.println
的作用:https://docs.oracle.com/javase/7/docs/api/java/io/PrintStream.html#println%28java.lang.Object%29
它说:
此方法首先调用String.valueOf(x)来获取打印 对象的字符串值,然后表现得好像它调用print(String) 然后是println()。
以下是String.valueOf
的作用:https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#valueOf%28java.lang.Object%29
它说:
如果参数为null,则字符串等于“null”;否则, 返回obj.toString()的值。
简而言之,打印对象将导致调用其toString
方法并打印它返回的内容。
答案 2 :(得分: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();
}