看这个代码:
public class D { @Override public String toString() { return "obj:"+this; } public static void main(String[] args) { System.out.println(new D()); } }
貌似很正常,但是这个代码是错误的,this会重复递归调用toString,最终抛出栈溢出异常:
Exception in thread "main" java.lang.StackOverflowError at java.lang.AbstractStringBuilder.ensureCapacityInternal(AbstractStringBuilder.java:113) at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:415) ...
应该返回super.toString().
时间: 2024-11-05 12:28:42