全局變量(或者屬性)的初始化問題


總結:定義的全局變量(即類的屬性)——數組、基本數據類型、其他引用類型變量,

  • 采用靜態初始化方式,即定義變量的同時進行初始化;
  • 采用動態初始化方式,只在屬性處定義變量,初始化放在方法中進行;
  • 錯誤操作:先定義屬性中的變量,接着換行再進行初始化。(詳細見下)

1.定義變量的時候,立刻初始化,即靜態初始化;

public class Test {
    int a = 1;//靜態初始化基本數據類型

    String[] s = {"Hello","World","你好,世界"};//靜態初始化引用類型數組
    Example[] e = {new Example(2019,"小明"),new Example(2018,"小紅")};

}
class Example{
    int id;
    String name;

    public Example(int id, String name) {
        this.id = id;
        this.name = name;
    }
}

2.只定義,最后在方法中進行初始化;

public class Test02 {
    int a;
    String[] s;
    Example[] e = new Example[2];
    public void se(){
        a = 1;//動態初始化,必須在方法中,進行
        e[0] = new Example(2019,"小明");//同理,數組的動態初始化也必須在方法中進行,靜態方法或者動態方法均可
        e[1] = new Example(2018,"小紅")
    }
}
class Example{
    int id;
    String name;

    public Example(int id, String name) {
        this.id = id;
        this.name = name;
    }
}

3、錯誤初始化操作(如下代碼報錯)

public class Test03 {
    int a;
    a = 1;//直接對全局變量(即屬性),先定義,接着初始化,這是錯誤的
    String[] s;
    s = {"ab","cd","ef"};
    Example[] e = new Example[2];
    e[0] = new Example(2019,"小明");//同理,數組也不能這樣初始化操作
    e[1] = new Example(2018,"小紅");
}
class Example{
    int id;
    String name;

    public Example(int id, String name) {
        this.id = id;
        this.name = name;
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM