Java - 两个类互相组合嵌套引用会爆炸吗?
Posted 程序员牧码
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java - 两个类互相组合嵌套引用会爆炸吗?相关的知识,希望对你有一定的参考价值。
Demo3.java
package tech.luxsun.interview.luxinterviewstarter.demo;
import java.time.LocalDateTime;
public class Demo3 {
private String sex;
private String name;
private Demo2 demo2;
public Demo3(String sex, String name) {
this.sex = sex;
this.name = name;
}
public Demo3() {
}
public Demo2 getDemo2() {
return demo2;
}
public void setDemo2(Demo2 demo2) {
this.demo2 = demo2;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Demo3{" +
"sex='" + sex + '\\'' +
", name='" + name + '\\'' +
", demo2=" + demo2 +
'}';
}
}
Demo2.java
package tech.luxsun.interview.luxinterviewstarter.demo;
public class Demo2 {
private String sex;
private String name;
private Demo3 demo3;
public Demo2() {
}
public Demo3 getDemo3() {
return demo3;
}
public void setDemo3(Demo3 demo3) {
this.demo3 = demo3;
}
public Demo2(String sex, String name) {
this.sex = sex;
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static void main(String[] args) {
Demo2 demo2 = new Demo2();
demo2.setName("Bob");
demo2.setSex("男");
Demo3 demo3 = new Demo3();
demo3.setName("Alice");
demo3.setSex("女");
demo2.setDemo3(demo3);
demo3.setDemo2(demo2);
System.out.println(demo2.toString());
System.out.println(demo3.getDemo2());
}
@Override
public String toString() {
return "Demo2{" +
"sex='" + sex + '\\'' +
", name='" + name + '\\'' +
", demo3=" + demo3 +
'}';
}
}
- 目前 2 个 Demo 都重写了 toString,输出结果
Exception in thread "main" java.lang.StackOverflowError
at java.lang.StringBuilder.append(StringBuilder.java:136)
at tech.luxsun.interview.luxinterviewstarter.demo.Demo2.toString(Demo2.java:58)
at java.lang.String.valueOf(String.java:2994)
at java.lang.StringBuilder.append(StringBuilder.java:131)
at tech.luxsun.interview.luxinterviewstarter.demo.Demo3.toString(Demo3.java:44)
at java.lang.String.valueOf(String.java:2994)
at java.lang.StringBuilder.append(StringBuilder.java:131)
……
- 注释掉其中 1 个 Demo toString,输出结果
Demo2{sex='男', name='Bob', demo3=tech.luxsun.interview.luxinterviewstarter.demo.Demo3@19469ea2}
Demo2{sex='男', name='Bob', demo3=tech.luxsun.interview.luxinterviewstarter.demo.Demo3@19469ea2}
以上是关于Java - 两个类互相组合嵌套引用会爆炸吗?的主要内容,如果未能解决你的问题,请参考以下文章