java static block of code block constructor configured

Directly on the code 

public class Study {

    public Study(){//构造方法
        System.out.println("init");
    }

    {//构造代码块
        System.out.println("hehe");
    }

    static {//静态代码块
        System.out.println("haha");
    }

    public static void main(String[] args) {
        Study s1 = new Study();
        Study s2 = new Study();
    }
}

Results of the

e71c0c5ac282a54c44efe08940092093b74.jpg

Conclusions: 1) and the static block of code execution priority is executed only once. 2) configured to perform block constructor priority, and each method call the constructor will be executed.

 

In the case of inheritance

public class Study {

    public Study(){//构造方法
        System.out.println("老子构造方法");
    }

    {//构造代码块
        System.out.println("老子构造代码块");
    }

    static {//静态代码块
        System.out.println("老子静态代码块");
    }

    public static void main(String[] args) {
        Study s1 = new Study1();
        Study s2 = new Study1();
    }
}

class Study1 extends Study{
    public Study1(){//构造方法
        System.out.println("儿子构造方法");
    }

    {//构造代码块
        System.out.println("儿子构造代码块");
    }

    static {//静态代码块
        System.out.println("儿子静态代码块");
    }
}

71a145f24d7f8878e11a37251b3ed4d695e.jpg

Conclusions: 1) static code block will always take precedence. 2) the parent building block Constructor priority subclass building block constructor.

Reproduced in: https: //my.oschina.net/kalnkaya/blog/1842039

Guess you like

Origin blog.csdn.net/weixin_34228662/article/details/91951391