首页 > 解决方案 > 在 java 中重写 toString()

问题描述

为什么 toString() 有效?我们没有叫它。它像构造函数一样工作。

public class Main {

    public static void main(String[] args) {
    // write your code here
        A a=new A();
        System.out.println(a);
    }
}
class A{
    @Override
    public String toString(){
        return "Hello";
    }
}

那么我们将删除println、设置断点并在调试模式下运行程序呢?

public class Main {

    public static void main(String[] args) {
        A a=new A();
        A a2=a;

    }
}
class A{
    @Override
    public String toString(){
        return "Hello";
    }
}

如我们所见,“Hello”设置为aand a2。为什么??

标签: javatostring

解决方案


当您使用 Java(和许多其他语言)调试代码时,IDE 使用相同语言的内置方法计算表达式。IDE 的对象的默认表示通常是字符串表示。

调试器调用toString方法来获取要在变量中显示的内容,并且由于您已经覆盖了它,因此调试器会向您显示Hello对象的默认描述(这是toString类中的默认实现Object)。

根据java.lang.Object源码,实现:

 177:   /**
 178:    * Convert this Object to a human-readable String.
 179:    * There are no limits placed on how long this String
 180:    * should be or what it should contain.  We suggest you
 181:    * make it as intuitive as possible to be able to place
 182:    * it into {@link java.io.PrintStream#println() System.out.println()}
 183:    * and such.
 184:    *
 185:    * <p>It is typical, but not required, to ensure that this method
 186:    * never completes abruptly with a {@link RuntimeException}.
 187:    *
 188:    * <p>This method will be called when performing string
 189:    * concatenation with this object.  If the result is
 190:    * <code>null</code>, string concatenation will instead
 191:    * use <code>"null"</code>.
 192:    *
 193:    * <p>The default implementation returns
 194:    * <code>getClass().getName() + "@" +
 195:    *      Integer.toHexString(hashCode())</code>.
 196:    *
 197:    * @return the String representing this Object, which may be null
 198:    * @throws OutOfMemoryError The default implementation creates a new
 199:    *         String object, therefore it must allocate memory
 200:    * @see #getClass()
 201:    * @see #hashCode()
 202:    * @see Class#getName()
 203:    * @see Integer#toHexString(int)
 204:    */
 205:   public String toString()
 206:   {
 207:     return getClass().getName() + '@' + Integer.toHexString(hashCode());
 208:   }

推荐阅读