首頁  >  問答  >  主體

请问关于 Java static 变量的问题?

public class StaticTest {

    private static String a;
    private static String b = "this is " + a;

    public static void main(String[] args) {
        a = "test";
        // I think the result is this is test
        // but the result is this is null, why?

        System.out.println(b);
    }


    //
    //  我本以为输出结果是 this is test
    // 没想到输出结果为 this is null, 这是什么原因

}
ringa_leeringa_lee2742 天前457

全部回覆(2)我來回復

  • 巴扎黑

    巴扎黑2017-04-18 10:58:42

    首先第一個:你在定義A變數時,就沒有賦初值,所以A為NULL,然後得到B自然就是this is null
    然後第二個:public static void main,編譯器在編譯這段程式碼時a,b先被main函數引用,你再更改a,a倒是被更改了,但b還是那個b,永遠都是this is null。你需要明白靜態函數運作的過程的意義。你的B沒有動態被set,當然得到的就算那個靜態b,而不會被動態編譯。

    回覆
    0
  • 黄舟

    黄舟2017-04-18 10:58:42

    這是關於JVM的類別初始化機制吧,字節碼轉為運行物件的三個過程裝載,連接,初始化。 。 。其中連接的準備過程會給a一個預設值null,因為StaticTest 具有main方法,被設定為JVM 啟動時的啟動類別會執行主動調用,進行類別的初始化,執行這兩行程式碼private static String a;private static String b = "this is " + a;所以b=this is null

    回覆
    0
  • 取消回覆