toString方法是Object里面的方法,所有类都是继承Object,所以“所有对象都有这个方法”。当你System.out.println()它的时候,如果它不是String类型,它会自动调用toString方法输出。而如果你想输出get的值,你只能用实例.get()去调用方法。
这是java10中println的源码,可以看到当参数是一个对象时会先调用 String.valueOf()方法来获取一个字符串
/**
* Prints an Object and then terminate the line. This method calls
* at first String.valueOf(x) to get the printed object's string value,
* then behaves as
* though it invokes {@link #print(String)} and then
* {@link #println()}.
*
* @param x The {@code Object} to be printed.
*/
public void println(Object x) {
String s = String.valueOf(x);
synchronized (this) {
print(s);
newLine();
}
}
String.valueOf()源码如下:
/**
* Returns the string representation of the {@code Object} argument.
*
* @param obj an {@code Object}.
* @return if the argument is {@code null}, then a string equal to
* {@code "null"}; otherwise, the value of
* {@code obj.toString()} is returned.
* @see java.lang.Object#toString()
*/
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
这样就可以看到,实际上println(一个对象)时默认调用的是其toString()方法而非get方法
我觉得你这个问题好蠢,你的逻辑都是混乱的,你输出的是类不是get方法,既然输出的是类怎么会给你输出get的返回值,System.out.println()
括号里的值会自动调用toString方法,所有的类都继承了Object,所以所有的类都有toString方法