java - 在 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”设置为a
and a2
。为什么??
解决方案
当您使用 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: }
推荐阅读
- swift - 与 viewcontroller 一起使用时的 swiftUI 导航栏标题设置
- laravel - 如何获取laravel中列不为空或为空的记录?
- node.js - Angular 9 SSR 空白页面呈现超时错误
- php - 如何通过单击超链接表格单元格并使用单击的 ID 从 SQL 数据库填充模型中的数据来使用 bootstrap 4 打开模式
- sparql - 在 Virtuoso SPARQL 查询编辑器中,ASK 查询返回 false,为什么?
- python - 如何使用 NumPy 直接创建一个数组,该数组由几个统一大小的元组/列表的 python 嵌套循环组成?
- java - 将基于 Java 的应用程序的新更改部署到商业服务器而不重新启动服务器
- sql - 使用内部连接检索记录
- php - 在 laravel 中进行身份验证时注册新用户
- c++ - 跨平台 GPU 计算