【问题标题】:Override toString() in java在 java 中重写 toString()
【发布时间】:2020-05-16 11:30:21
【问题描述】:

为什么 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。 为什么??

【问题讨论】:

  • 请用英文发帖。
  • 为什么 toString() 有效?我们没有叫它。它像构造函数一样工作
  • 我们实际上看不到,你可以附上调试器的截图,这样大家的问题就会更清楚了。
  • 因为 toString() 是在对象上定义的,然后在调用 println 时使用它来获取表示对象的字符串,并在调试器中用于显示值。

标签: java tostring


【解决方案1】:

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

调试器调用toString 方法来获取要在变量中显示的内容,并且由于您已经覆盖了它,因此调试器会向您显示Hello,而不是对象的默认描述(这是toString 在类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:   }

【讨论】:

  • 你的意思是当任何程序启动时 toString() 总是被收集?
  • 没有。总是在调试它(在调试器中查看特定变量)或打印对象,或尝试以任何其他方式将其隐式转换为字符串时
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-06
  • 1970-01-01
  • 2014-01-19
  • 1970-01-01
相关资源
最近更新 更多