Java静态方法块、非静态方法块、构造方法、静态方法执行顺序

示范类StaticTest.java


public class StaticTest {
    {//只有当创建对象的时候执行
        System.out.println("H1");
    }
    static {//加载该类就执行,仅一次加载   程序执行中一直使用
        System.out.println("H2");
    }
    StaticTest()
    {
        System.out.println("H3");
    }
static void printhello()
{
    System.out.println("H4");
}
    public static void main(String[] args) {
        System.out.println("1");
        StaticTest st;
        System.out.println("2");
        new StaticTest();
        System.out.println("3");
        StaticTest.printhello();
        System.out.println("4");
        StaticTest st2=new StaticTest();
        System.out.println("5");
        st2.printhello();
    }
}

程序执行结果

H2
1
2
H1
H3
3
H4
4
H1
H3
5
H4

知识点:

静态方法块在加载该类的时候执行,且只执行一次。static{}

非静态方法块在创建对象时执行,创建一次执行一次。{}

静态方法块优先于非静态方法块执行,方法块优先于构造方法执行     优先级 static{} >    {}   >    StaticTest(){}

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章