为什么这个具有相同类的实例变量的类会导致StackOverflowError,而类似的类与相同类型的静态变量不相同?

sar*_*hak -4 java

我的问题与另一个问题有关:如何在类本身内部创建类的实例?

我创建了两个类,如下所示:

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

而另一个:

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

我不明白为什么第一个代码(没有静态变量)给出了堆栈溢出错误但是当我声明实例变量是静态的(第二种情况)时我没有错误.static关键字在这里有什么区别?

Era*_*ran 6

只要创建了类的新实例,第一个代码段就会创建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...
Run Code Online (Sandbox Code Playgroud)

第二个片段,因为此处变量是静态的,在初始化类时会创建类的实例.创建类的新实例时,没有无限递归.

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
Run Code Online (Sandbox Code Playgroud)