1. 简述
Java 中的每个类都是继承自 Object。且 Java 中唯二的两个字符串重载操作符 “+”、“+=” 会在有字符串的情况下,将其余对象默认转换为字符串来处理。下面代码想输出对象地址。
2. 代码演示
代码:
public class StringLoop {
@Override
public String toString() {
return "StringLoop address: " + this + "\n";
}
public static void main(String[] args) {
List<StringLoop> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
list.add(new StringLoop());
}
System.out.println(list);
}
}
输出:
Exception in thread "main" java.lang.StackOverflowError
3. 说明
“StringLoop address: " + this + “\n” 这里发生了自动类型转换,由 StringLoop 转换成了 String 类型。因为编译器看到一个 String 后面跟着一个”+",而后面的对象不是 String,于是编译器是这将 this 转换为 String。它怎么转换那?正是通过调用 this.toString() 方法,于是发生了递归调用。