【问题标题】:Why does this class with instance variable of same class cause StackOverflowError while similar class with static variable of same type does not? [duplicate]为什么具有相同类的实例变量的此类会导致 StackOverflowError 而具有相同类型的静态变量的类似类不会? [复制]
【发布时间】:2017-05-08 03:52:27
【问题描述】:

我的问题与另一个问题有关:How does creating a instance of class inside of the class itself works?

我创建了两个类如下:

class Test {
  Test buggy = new Test();
  public static void main (String[] args) {
    Test test = new Test();
    System.out.println("Done");
  }
}

还有一个:

class Test {
  static Test buggy = new Test();
  public static void main (String[] args) {
    Test test = new Test();
    System.out.println("Done");
  }
}

我不明白为什么第一个代码(没有静态变量)会出现堆栈溢出错误,但是当我将实例变量声明为静态(第二种情况)时,我没有收到任何错误。 static 关键字在这里有什么不同?

【问题讨论】:

  • 在第一个代码中,您创建了一个 Test 实例,并在其中创建了另一个实例。这会创建一个无限循环。
  • 在初始化Test 时,先了解一下会发生什么。初始化单个 Test 时会发生什么?它有一个变量buggy,它被初始化,它的类型是Test。这个Test 也有一个buggy 类型的变量Test,它也想被初始化。你猜怎么了?你现在有另一个变量buggy 想要被初始化。这种情况会一直发生,直到您的 Stack 实例溢出 Test

标签: java


【解决方案1】:

每当您的类的新实例被创建时,第一个 sn-p 都会创建您的 Test 类的新实例。因此无限递归和堆栈溢出。

Test test = new Test(); // creates an instance of Test which triggers
                        // initialization of all the instance variables,
                        // so Test buggy = new Test(); creates a second
                        // instance of your class, and initializes its
                        // instance variables, and so on...

第二个 sn-p,因为这里的变量是静态的,所以在初始化类时创建类的实例。当你的类的新实例被创建时,没有无限递归。

Test test = new Test(); // this time buggy is not an instance variable, so it
                        // has already been initialized once, and wouldn't be
                        // initialized again

【讨论】:

    【解决方案2】:

    静态字段仅在类加载器首次加载 Test 类时初始化一次。

    【讨论】:

      猜你喜欢
      • 2013-10-16
      • 1970-01-01
      • 2015-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-22
      相关资源
      最近更新 更多