System.out.println使用getClass()在相同的对象类型上打印不同的字符串

问题描述 投票:1回答:3

我已经读过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”?预先谢谢你。

java
3个回答
3
投票

因为getClass()将返回Class的实例

public final Class<?> getClass()

并且当您打印Class实例时,将调用toString返回其名称,这是Java中toStringClass实现

public String toString() {
    return (isInterface() ? "interface " : (isPrimitive() ? "" : "class "))
        + getName();
}

1
投票

Class.toString的定义不同,正好生成您看到的输出。它只是打印班级的名称。该类中没有Object.toString默认调用


0
投票

在下面的语句中,toString()Car方法被调用:

System.out.println(c);

在下面的语句中,toString()Class方法被调用:

System.out.println(c.getClass());

由于尚未覆盖toString()Car方法,因此将调用toString()Object方法,为您提供类似于Car@xxx的输出。

© www.soinside.com 2019 - 2024. All rights reserved.