請問關(guān)于 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); } // // 我本以為輸出結(jié)果是 this is test // 沒想到輸出結(jié)果為 this is null, 這是什么原因}
問題解答
回答1:首先第一個(gè):你在定義A變量時(shí),就沒有賦初值,所以A為NULL,然后得到B自然就是this is null然后第二個(gè):public static void main,編譯器在編譯這段代碼時(shí)a,b先被main函數(shù)引用,你再更改a,a倒是被更改了,但b還是那個(gè)b,永遠(yuǎn)都是this is null。你需要明白靜態(tài)函數(shù)運(yùn)行的過程的意義。你的B沒有動(dòng)態(tài)被set,當(dāng)然獲得的就算那個(gè)靜態(tài)b,而不會(huì)被動(dòng)態(tài)編譯。
回答2:這是關(guān)于JVM的類初始化機(jī)制吧,字節(jié)碼轉(zhuǎn)為運(yùn)行對象的三個(gè)過程裝載,連接,初始化。。。其中連接的準(zhǔn)備過程會(huì)給a賦予默認(rèn)值null,因?yàn)?StaticTest 具有main方法,被設(shè)定為 JVM 啟動(dòng)時(shí)的啟動(dòng)類會(huì)執(zhí)行主動(dòng)調(diào)用,進(jìn)行類的初始化,執(zhí)行這兩行代碼 private static String a;private static String b = 'this is ' + a;所以b=this is null
相關(guān)文章:
1. 關(guān)docker hub上有些鏡像的tag被標(biāo)記““This image has vulnerabilities””2. docker-compose中volumes的問題3. boot2docker無法啟動(dòng)4. nignx - docker內(nèi)nginx 80端口被占用5. docker安裝后出現(xiàn)Cannot connect to the Docker daemon.6. dockerfile - 為什么docker容器啟動(dòng)不了?7. java - SSH框架中寫分頁時(shí)service層中不能注入分頁類8. node.js - antdesign怎么集合react-redux對input控件進(jìn)行初始化賦值9. 關(guān)于docker下的nginx壓力測試10. docker容器呢SSH為什么連不通呢?

網(wǎng)公網(wǎng)安備