Creating object using static keyword in Java

后端 未结 2 1096
萌比男神i
萌比男神i 2021-02-19 08:41
class abc {
    int a = 0;
    static int b;
    static abc h = new abc(); //line 4

    public abc() {
        System.out.println(\"cons\");
    }

    {
        System         


        
2条回答
  •  时光说笑
    2021-02-19 08:52

    Static fields initialization and static blocks are executed in the order they are declared. In your case, the code is equivalent to this after separating declaration and initialization:

    class abc{
        int a;
        static int b;
        static abc h;//line 4
    
        static {
            h = new abc();//line 4 (split)
            System.out.println("stat");
        }
    
        public abc() {
            a = 0;
            System.out.println("ini");
            System.out.println("cons");
        }
    }
    
    public class ques{
        public static void main(String[] args) {
            System.out.println(new abc().a);
        }
    }
    

    So when you reach line 4 from your code, the static initialization is actually being executed and not finished yet. Hence your constructor is called before stat can be printed.

提交回复
热议问题