Getting exception in thread “main” java.lang.StackOverflowError

后端 未结 4 1316
臣服心动
臣服心动 2021-01-24 02:09

I am new to Java and OOPs and here is my issue. When I run the below code, I get the

Exception in thread \"main\" java.lang.StackOverflowError.

4条回答
  •  旧巷少年郎
    2021-01-24 02:58

    The problem is that you can't do something like this:

    Class Try{
    Try try = new Try();
    public static void main(String[] arg)
    {
    Try try1 = new Try();
    }
    

    The issue with above code is that first the execution will start with your main method(ofcourse in this particular case :) ) then the try1 object will get created and all of the Class fields will get initialized, since you created an object of the same class you are in as a Class Field() it will try to re-initialize the Class fields, ending up in an infinite loop and inevitably the Famous STACK OVERFLOW error!

    Now, talking in context of your question:

    App2 a2 = new App2();
    JavaApplication1 ja =new JavaApplication1(); //remove this line, it is causing the SO-error!!!
    

提交回复
热议问题