Reputation: 49
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
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:
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
Reputation: 328
The field interviewQuestion is creating another NucleousInterviewQuestion object, and this new object is creating another one and so on - recursion...
Upvotes: 2