简体   繁体   English

为什么 class “测试”中的以下代码不会使用 static 关键字给出 stackoverflow 错误

[英]Why the following code in class “test” don't give stackoverflow error with static keyword

Why the following code in class test don't give stackoverflow error with static keyword?为什么 class test中的以下代码不会使用static关键字给出 stackoverflow 错误?

import java.util.*;

public class Main {

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

    static  test p = new test() ;  
}

Got the answer得到了答案

  1. static variables in a class are initialized before any object of that class can be created. class 中的 static 变量在可以创建 ZA2F2ED4F8EBC2CBB4C21A29DC40AB6 的任何 object 之前初始化。

2)static variables,methods are related to class rather than a particular instance. 2)静态变量,方法与 class 相关,而不是特定实例。

as p is static - it is initialized only once, so new test() won't be executed a second time - thus no stack overflow因为 p 是 static - 它只初始化一次,所以 new test() 不会第二次执行 - 因此没有堆栈溢出

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM