繁体   English   中英

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

[英]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() ;  
}

得到了答案

  1. class 中的 static 变量在可以创建 ZA2F2ED4F8EBC2CBB4C21A29DC40AB6 的任何 object 之前初始化。

2)静态变量,方法与 class 相关,而不是特定实例。

因为 p 是 static - 它只初始化一次,所以 new test() 不会第二次执行 - 因此没有堆栈溢出

暂无
暂无

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

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