System.out
is a PrintStream
. Printstream defines several versions of the println()
function to handle numbers, strings, and so on. When you call PrintStream.println()
with an arbitrary object as a parameter, you get the version of the function that acts on an Object
. This version of the function
...calls at first String.valueOf(x) to get the printed object's string value...
Looking at String.valueOf(Object)
, we see that it returns
if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.
So, long story short, System.out.println(someObject)
calls that object's toString()
function to convert the object to a string representation.
If your object defines its own toString()
function, then that is what will be called. If you don't provide such a function, then your object will inherit toString()
from one of its parent classes. In the worst case, it will inherit Object.toString()
. That version of toString() is defined to return
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.
Or, in other words:
getClass().getName() + '@' + Integer.toHexString(hashCode())
So, when you call System.out.println()
on an object that doesn't define its own version of toString(), you might get the Object
version which looks like "classname@someHexNumber".
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…