在 java 中覆盖 toString()

Override toString() in java

为什么 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" 设置为 aa2。 为什么??

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

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

根据java.lang.Object source code,实施:

 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:   }