我已经读过this question,但是我对此并不完全满意。这是我的代码:
public static void main(String args[]){
Car c = new Car();
System.out.println(c);
System.out.println(c.getClass());
}
输出:
Car@xxx
Car
而且我不明白为什么在第一种情况下它还会打印hashCode而在第二种情况下却不打印hashCode。我已经了解了println(Object obj)
的定义及其使用的方法,并且它们实际上是相同的,在最深层的堆栈调用中,toString()
的定义如下:
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
所以为什么在输出中看不到“ @xxx”?预先谢谢你。
因为getClass()将返回Class
的实例
public final Class<?> getClass()
并且当您打印Class
实例时,将调用toString返回其名称,这是Java中toString的Class
实现
public String toString() {
return (isInterface() ? "interface " : (isPrimitive() ? "" : "class "))
+ getName();
}
Class.toString
的定义不同,正好生成您看到的输出。它只是打印班级的名称。该类中没有Object.toString
默认调用
在下面的语句中,toString()
的Car
方法被调用:
System.out.println(c);
在下面的语句中,toString()
的Class
方法被调用:
System.out.println(c.getClass());
由于尚未覆盖toString()
的Car
方法,因此将调用toString()的Object
方法,为您提供类似于Car@xxx
的输出。