互相依赖引用,toString() 导致StackOverflowError

Exception in thread "main" java.lang.StackOverflowError

public class A {
private B b;
public B getB() {
return b;
}
public void setB(B b) {
this.b = b;
}
public A(B b) {
this.b = b;
}
public A() {
}
@Override
public String toString() {
return "A{" +
"b=" + b +
'}';
}
}


public class B {
private A a;
public A getA() {
return a;
}
public void setA(A a) {
this.a = a;
}
public B(A a) {
this.a = a;
}
public B() {
}
@Override
public String toString() {
return "B{" +
"a=" + a +
'}';
}
}


public class StackDemo {

public static void main(String[] args) {
A a = new A();
B b = new B(a);
a.setB(b);
a.toString();
}
}


Exception in thread "main" java.lang.StackOverflowError
at java.lang.StringBuilder.append(StringBuilder.java:136)
at com.enjoy.mj.stackd.A.toString(A.java:23)
at java.lang.String.valueOf(String.java:2979)
at java.lang.StringBuilder.append(StringBuilder.java:131)
at com.enjoy.mj.stackd.B.toString(B.java:23)

posted @ 2019-12-06 16:43  魔杰Lee  阅读(530)  评论(0编辑  收藏  举报