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

时间:2017-03-24 08:21:42

标签: 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();
 }
}

2 个答案:

答案 0 :(得分:6)

这里:

public class NucleousInterviewQuestion {
  NucleousInterviewQuestion interviewQuestion = new  NucleousInterviewQuestion();

创建无休止的递归。

重点是:您在主要方法中调用new。执行此操作时,运行属于此类的“init”代码。 “init”代码包括:

  • 字段初始化语句
  • 和构造函数调用

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

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

public class Example {
  Example other;

  public Example() {
    other = null;
  }

  public Example(Example other) {
    this.other = other;
  }

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

答案 1 :(得分:2)

字段interviewQuestion正在创建另一个NucleousInterviewQuestion对象,这个新对象正在创建另一个 - 依此类推 - 递归......

相关问题