线程"main"中的异常:java.lang.StackOverflowError,为什么?

Bhu*_*mar 1 java

这是我的代码; 导致StackOverflow错误:

public class NucleousInterviewQuestion {

NucleousInterviewQuestion interviewQuestion = new  NucleousInterviewQuestion();

public NucleousInterviewQuestion() {
    // TODO Auto-generated constructor stub
}

public static void main(String[] args) {
    NucleousInterviewQuestion interviewQuestion= new NucleousInterviewQuestion();
 }
}
Run Code Online (Sandbox Code Playgroud)

Gho*_*ica 6

这里:

public class NucleousInterviewQuestion {
  NucleousInterviewQuestion interviewQuestion = new  NucleousInterviewQuestion();
Run Code Online (Sandbox Code Playgroud)

创造了无尽的递归.

关键是:你打电话给new你的主要方法.执行此操作时,运行属于此类的"init"代码."init"代码包括:

  • 字段init语句
  • 和构造函数调用

你有一个具有init代码的字段...... new再次调用; 对于同一个班级.

在这个意义上的"解决方案":了解如何初始化类.当然,类可以有引用其他对象的字段; 甚至是同一类的对象; 但是你需要(例如)类似的东西:

public class Example {
  Example other;

  public Example() {
    other = null;
  }

  public Example(Example other) {
    this.other = other;
  }
Run Code Online (Sandbox Code Playgroud)

这样您就可以引用同一个类中的另一个对象; 没有创建递归.