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

后端 未结 4 1315
臣服心动
臣服心动 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:52

    Your class JavaApplication1 has field JavaApplication1 ja which holds another instance of JavaApplication1 class, which also has its own ja field which holds another instance of JavaApplication1, and so on and on.

    In other words, when you create instance of JavaApplication1 this instance creates its inner instance of JavaApplication1 and this inner instance creates another JavaApplication1 instance, which again creates instance JavaApplication1... until stack will be full.

    So when you run this code in your main method

    JavaApplication1 ja1 = new JavaApplication1();
    

    something like this happens

           +-----------------------------------------------+
    ja1 -> | JavaApplication1 instance                     |
           +-----------------------------------------------+
           |                                               |
           |       +------------------------------------+  |
           | ja -> | JavaApplication1 instance          |  |
           |       +------------------------------------+  |
           |       |                                    |  |
           |       |       +-------------------------+  |  |
           |       | ja -> |JavaApplication1 instance|  |  |
           |       |       +-------------------------|  |  |
           |       |       |                         |  |  |
           |       |       | ja -> ....              |  |  |
           |       |       +-------------------------+  |  |
           |       +------------------------------------+  |
           +-----------------------------------------------+
    

    Anyway I don't see where ja field is ever used, so consider removing it from your code.

提交回复
热议问题