Recursive calls resulting in an exception

public class TestClass {

    TestClass classIn = new TestClass(); 
    public static void main(String[] args) {
        TestClass classIn = new TestClass(); 
    }
}

      

Can anyone tell me why this is causing a stack overflow?

+3


source to share


3 answers


The error would be that whenever you try to instantiate TestClass

, it tries to instantiate itself again on the line -

TestClass classIn = new TestClass(); 

      



And this continues recursively until the stack overflows. Remove that line and you should be fine.

+2


source


Your instance variable is classIn

initialized every time you create an instance TestClass

. Therefore, every time you create an instance TestClass

, you immediately create another instance, which results in infinite recursion.

The first instance is created in the main method:



TestClass classIn = new TestClass();

      

Before the constructor is executed TestClass

, the instance variables ( classIn

in your case) are initialized, so another instance is created which triggers the creation of another instance, etc ... (while the stack overflows).

+1


source


As mentioned above, you are in infinite recursion and there is only so much you can do on a computer before. A very important rule for recursion is: ALWAYS, ALWAYS, WE HAVE A BASIC CLASS!

Think about an example of factorial recursion:

int factorial(int n)
{
if(n = 0)
  return 1;
else
  return n * factorial(n-1);
}

      

Notice the base case where you, a human, can manually calculate it. This case prevents overflow, since without your code the loop will simply execute. Suppose I have 3 without this base case. So you get 3 * 2 * 1 * 0 * -1 * -2 ....

+1


source







All Articles