Java基礎(chǔ):五、成員初始化 (6)

成員初始化

Java 盡力保證:所有變量在使用前都能得到恰當(dāng)?shù)某跏蓟?。對于方法的局部變量,必須在使用時(shí)為變量賦一個(gè)默認(rèn)值,否則編譯器會(huì)報(bào)錯(cuò)

對于類的數(shù)據(jù)成員(即字段) 是基本類型,如果定義是沒有初值,編譯器也會(huì)給一個(gè)初始值, 如果是在類里定義一個(gè)對象引用時(shí),如果不將其初始化,此引就會(huì)獲得一只特殊值null

class InitialValues{
    // 只定義字段不賦值
    boolean t;
    char c;
    byte b;
    short s;
    int i;
    long l;
    float f;
    double d;
    InitialValues reference;
    void printInitialValues(){
        System.out.println("Data type Initial value");
        System.out.println("boolean " + t); // boolean 初始值false
        System.out.println("char " + c); // char 初值為0,所以為空
        System.out.println("byte " + b); // byte 初值為0
        System.out.println("short " + s); // short 初值為0
        System.out.println("int " + i); // int 初值為0
        System.out.println("long " + l); // long 初值為0
        System.out.println("double " + d); // double 初值為0.0
        System.out.println("InitialValues " + reference); // 引用類型reference 初值為null
    }

    public static void main(String[] args) {
        InitialValues initialValues = new InitialValues();
        initialValues.printInitialValues();
        /**
         * 可以使用這種寫法
         * new InitialValues.printInitialValues();
         */
    }
}

指定初始化 就是在定義類成員變量的地方為其賦值

class Depth{}

class InitialValues{
    // 定義字段并賦值
    boolean t = true;
    char c = 'x';
    byte b = 47;
    short s = 0xff;
    int i = 999;
    long l = 1;
    float f = 3.14f;
    double d = 3.14159;
    InitialValues reference;
    Depth dep = new Depth();  // 為引用類型賦值,如果沒有指定初始值就嘗試使用,會(huì)出現(xiàn)運(yùn)行時(shí)錯(cuò)誤
}

通過調(diào)用某個(gè)方法來提供初值 ,并且這個(gè)方法也可以帶有參數(shù),但這些參數(shù)必須是已經(jīng)被初始化了的

class MethodInit{
    int i = f(); // 通過調(diào)用某個(gè)方法來提供初值
    int j = g(i); // 方法可以帶已經(jīng)初始化了的參數(shù)
    int f(){
        return 11;
    }
    int g(int n){
        return n * 10;
    }   
}

但是這樣寫會(huì)報(bào)錯(cuò):

class MethodInit{

    // int j = g(i); // 會(huì)報(bào)錯(cuò) 
    int i = f(); // 通過調(diào)用某個(gè)方法來提供初值
    int f(){
        return 11;
    }
    int g(int n){
        return n * 10;
    }   
}

上述程序的正確性取決于初始化的順序,而與其編譯方式無關(guān)。所以,編譯器對這種“向前引用”報(bào)錯(cuò)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容