非靜態屬性、靜態屬性、靜態代碼塊、普通代碼塊、構造函數執行順序

知識點

  1. 靜態屬性和靜態代碼塊
    按代碼中定義先後順序執行
    這兩者優於其他順序
    都只是在類初始化的時候,加載一次
  2. 非靜態屬性
    在普通代碼塊之前加載
    每次新建對象的時候,都會執行
  3. 普通代碼塊
    在構造函數之前執行
    每次新建對象的時候,都會執行
  4. 構造函數
    在構造函數之前執行

總結:

  • 靜態屬性和靜態方法,是在類初始化階段執行的,屬於 “類”這個級別的,只加載一次
  • 非靜態屬性、普通代碼塊和構造函數,屬於“對象”級別的,每次新建對象都會加載一次

例子:

public class Test {

    public static void main(String[] args) {

        Zi z1 = new Zi();

        System.out.println("----------------------------");

        Zi z2 = new Zi();
    }
}
class Fu{
    private static Fu f1 = new Fu(); //Fu的靜態屬性
    private Other other = new Other(); //Fu的非靜態屬性

    public Fu(){
        System.out.println("Fu的構造函數");
    }

    static{
        System.out.println("Fu的靜態代碼塊");
    }

    {
        System.out.println("Fu的普通代碼塊");
    }
}

class Zi extends Fu{
    private static Zi z1 = new Zi(); //Zi的靜態屬性

    public Zi(){
        System.out.println("Zi的構造函數");
    }

    static{
        System.out.println("Zi的靜態代碼塊");
    }

    {
        System.out.println("Zi的普通代碼塊");
    }
}

class Other{
    public Other(){
        System.out.println("Other構造函數");
    }
}

結果:

Other構造函數
Fu的普通代碼塊
Fu的構造函數
Fu的靜態代碼塊
Other構造函數
Fu的普通代碼塊
Fu的構造函數
Zi的普通代碼塊
Zi的構造函數
Zi的靜態代碼塊
Other構造函數
Fu的普通代碼塊
Fu的構造函數
Zi的普通代碼塊
Zi的構造函數
----------------------------
Other構造函數
Fu的普通代碼塊
Fu的構造函數
Zi的普通代碼塊
Zi的構造函數

結果分析:
在這裏插入圖片描述

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