This question already has an answer here:
-
stackoverflow error in class constructor
2 answers
-
Why am I getting a StackOverflowError exception in my constructor
3 answers
This is my code :
public class ConstructorsDemo{
public static void main(String a[]){
Cons1 c1 = new Cons1();
}
}
class Cons1{
Cons1 c = new Cons1();// the error is in this line
Cons1(){
//does somwthing
}
}
So I get an infinite loop error here (Stackoverflow).
However it's fine if I comment out any of the two objects I have created.
How is the object c
in my code causing Stackoverflow error?
First point: this is infinite recursion, not an infinite loop. There's a big difference. There are perfectly legitimate reasons to use infinite loops and they will not, in general, cause stack overflow exceptions. However, there are no legitimate use cases for infinite recursion and its use will invariably lead to a stack overflow exception. (I suppose you could maybe argue for infinite tail recursion in a few odd situations for languages that have that but still...) If you get a stack overflow exception, it's almost certainly infinite recursion rather than an infinite loop.
The basic problem here, as others have pointed out, is that every time you call "new" it, in turn, creates a new object, which in turn creates a new object, and so on and so forth.
Cons1 c = new Cons1();
Lets have a look at your class.
It has an (empty) constructor, and a field of the same type as the class.
And that field is initialized directly in place.
Thing is: there is a well-defined process in Java that dictates how/when constructors are called, and how fields of a class are initialized. And well, member fields are initialized as part of calls to "new".
Leading to: when "new" is called in your main class, a new Cons1 object should be created and initialized. That Cons1 object has that Cons1 field. Which requires a new Cons1 object to be initialized with ... and so on.
And that is how you created your first never-ending recursion in Java.
Cons1 c = new Cons1();//
Please remove this statement and initialize it wherever you are going to use it . Code is recursive .
you're creating the object recursively,each time you create the object this is why you got the infinite loop and witch causes the stack overflow