Java成員變量初始化和執行順序

成員變量的初始化

  1. 在變量聲明出初始化
  2. 使用初始化塊初始化
  3. 使用構造器初始化

初始化執行順序

  1. 聲明處初始化和初始化塊執行早於構造器
  2. 聲明處初始化和初始化塊按照代碼的順序執行,先聲明的先執行
public class Init {
    //變量聲明處初始化
    int age = f();
    //初始化塊初始化
    {
        System.out.println("初始化塊執行");
        age=10;
    }
    //構造器初始化
    public Init(){
        age =10;
        System.out.println("構造器執行");
    }
    public int f(){
        System.out.println("聲明處初始化");
        return 3;
    }
    public static void main(String[] args) {
        Init in = new Init();
    }

}

創建對象,成員變量先分配空間,變量的值爲成員變量的默認值,分配空間完成後才進行初始化。

public class Init2 {
    {
        System.out.println("age ="+this.age);
    }
    int age = f();
    int a = 100;
    public int f(){
        System.out.println("a的值:"+a);
        return 3;
    }
    public static void main(String[] args) {
        Init2 in = new Init2();
    }
}
//age =0
//a的值:0
發佈了35 篇原創文章 · 獲贊 10 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章