【问题标题】:What is the flow of the program and Why it's stackOverFlow Error [duplicate]程序的流程是什么以及为什么它是stackOverFlow错误[重复]
【发布时间】:2019-08-14 10:46:03
【问题描述】:

为什么这个程序给出这个异常

"Exception in thread "main" java.lang.StackOverflowError at com.Test.<init>(Test.java:5)"

代码:

public class Test {

    Test t  = new Test();

    public static void main(String[] args) {
        Test t  = new Test();
    }
}

【问题讨论】:

  • 每次创建Test 的新实例时,都会创建Test 的另一个实例(即Test t = new Test(); 字段)。这就是您创建堆栈溢出的原因。至于流程,您可能应该获取一些基本教程。

标签: java


【解决方案1】:

发生这种情况是因为您将实例级变量初始化为类的实例,在该类中它自己定义,导致无限递归,并且 JVM 抛出 StackOverflowError

  • Test 的新实例在 main 方法中创建 Test,它将 Test 初始化为实例级变量,它创建 Test,将 Test 初始化为实例级变量等...

要修复它,请删除类中的第一行代码并使用以下代码:

public class Test {

    public static void main(String[] args) {    // this static method is called once upon 
        Test t  = new Test();                   // the start and creates an instance once
    }
}

【讨论】:

    【解决方案2】:

    每个类实例都调用新的类实例(无休止地),因此 StackOverflowError

    只需从类中删除未使用的字段:

    public class Test {   
    
        public static void main(String[] args) {
            Test t  = new Test();
        }
    }
    

    【讨论】:

      【解决方案3】:

      StackOverFlowError 即将到来,因为您正在创建与实例级别变量相同的类对象。因此,无论何时创建此类的实例,它都会在内部创建 Test 类的实例 [正如您将其定义为实例级变量],因此它将再次创建 Test 类的实例,依此类推......

      因此,您必须按如下方式删除实例级对象创建:-

      public class Test {
      
          public static void main(String[] args) {
              Test t  = new Test();
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2022-01-22
        • 1970-01-01
        • 2011-07-21
        • 2012-02-22
        • 2014-03-04
        • 2011-06-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多