简体   繁体   中英

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?

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.

2)static variables,methods are related to class rather than a particular instance.

as p is static - it is initialized only once, so new test() won't be executed a second time - thus no stack overflow

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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