Bhupesh Kumar
Bhupesh Kumar

Reputation: 49

Exception in thread "main": java.lang.StackOverflowError,Why?

This is my code; resulting in that StackOverflow error:

public class NucleousInterviewQuestion {

NucleousInterviewQuestion interviewQuestion = new  NucleousInterviewQuestion();

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

public static void main(String[] args) {
    NucleousInterviewQuestion interviewQuestion= new NucleousInterviewQuestion();
 }
}

Upvotes: 2

Views: 3972

Answers (2)

GhostCat
GhostCat

Reputation: 140457

This here:

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

creates an endless recursion.

The point is: you call new in your main method. When you do that, you run the "init" code that belongs to this class. "init" code consists of:

  • field init statements
  • and a constructor call

And you got one field which has init code ... that calls new again; for the very same class.

The "solution" in that sense: understand how classes are initialized. Of course classes can have fields that reference other objects; even objects of the same class; but then you need (for example) something like:

public class Example {
  Example other;

  public Example() {
    other = null;
  }

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

This way you can reference to another object from the same class; without creating a recursion.

Upvotes: 7

KiteUp
KiteUp

Reputation: 328

The field interviewQuestion is creating another NucleousInterviewQuestion object, and this new object is creating another one and so on - recursion...

Upvotes: 2

Related Questions