Search code examples
javaobjectconstructorstack-overflow

Why do I get Infinite loop(Stackoverflow error) while creating an object in a class with constructor?


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?


Solution

  • 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();