Java基礎——Java初始化順序,代碼詳解

代碼

package test;

class MainFather{
    static {System.out.println("this is in MainFather");}
    MainFather(){System.out.println("this is in MAINFATEHR,CONSTRUCTOR");}
}

public class Main extends MainFather{
    public static void main(String[] Args){
        new Main().new test().hello();
        new StaticClass();
        hi();
        System.out.println("world");

    }
    static {
        System.out.println("hello");
    }
    static void hi(){
        System.out.println("hi,I am in main,static member method");
    }
    class test{
        void hello(){
            System.out.println("this inner test");
        }

    }
}
class StaticClass {
    static {
        System.out.println("hi");
    }
    StaticClass(){
        System.out.println("this is in Constructor");
    }
}

結果

這裏寫圖片描述

結果分析

父類靜態代碼塊→子類靜態代碼塊→父類構造方法→子類構造方法→正常函數執行順序

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