Java 靜態(tài)數(shù)據(jù)初始化的示例代碼
無論創(chuàng)建多少個對象,靜態(tài)數(shù)據(jù)都只占用一份存儲區(qū)域。static關(guān)鍵字不能應(yīng)用于局部變量,因此它只能作用于域。如果一個域是靜態(tài)的基本類型域,且也沒有對它進(jìn)行初始化,那么它就會獲得基本類型的標(biāo)準(zhǔn)初始值;如果它是一個對象引用,那么它的默認(rèn)初始值就是null
class Bowl { public Bowl(int marker) { System.out.println('Bowl(' + marker + ')'); } void f1(int marker) { System.out.println('f1(' + marker + ')'); }} class Table { static Bowl bowl = new Bowl(1); public Table() { System.out.println('Table()'); bowl2.f1(1); } void f2(int marker) { System.out.println('f2(' + marker + ')'); } static Bowl bowl2 = new Bowl(2);} class Cupboard { Bowl bowl3 = new Bowl(3); static Bowl bowl4 = new Bowl(4); public Cupboard() { System.out.println('Cupboard()'); } void f3(int marker) { System.out.println('f3(' + marker + ')'); } static Bowl bowl5 = new Bowl(5);} public class StaticInit { public static void main(String[] args) { //第三步 System.out.println('Creating new Cupboard in main'); //第四步 //因?yàn)镃upboard內(nèi)的靜態(tài)變量已經(jīng)初始化完成,所以不再初始化(無論創(chuàng)建多少個對象,靜態(tài)數(shù)據(jù)都是只占用一份存儲區(qū)域) //但是里邊的類成員變量 bowl3 還是需要進(jìn)行二次初始化的,因?yàn)槟氵@是new對象,所以打印 Bowl(3) //然后調(diào)用該對象的無參構(gòu)造函數(shù),打印 Cupboard() new Cupboard(); //第五步 System.out.println('Creating new Cupboard in main'); //第六步 //和第四步一樣,執(zhí)行初始化,打印 Bowl(3),然后調(diào)用無參構(gòu)造函數(shù),打印 Cupboard() new Cupboard(); //第七步 table.f2(111); //第八步 cupboard.f3(111); } //Java 數(shù)據(jù)類型、對象引用 和 構(gòu)造器 之間的初始化順序 https://www.sunjs.com/article/detail/debedcef327c4872933e0b2f1ac7cb71.html //第1步: //先初始化靜態(tài)代碼塊、 //Table 類中也含有靜態(tài)引用變量,所以先去執(zhí)行bowl引用指向的對象的創(chuàng)建,所以先打印 Bowl(1) //然后該類中還有一個靜態(tài)對象,所以立即去初始化這個靜態(tài)對象,然后打印 Bowl(2) //執(zhí)行完成以后,正式創(chuàng)建對象,執(zhí)行Table類的默認(rèn)無參構(gòu)造函數(shù),打印 Table() //構(gòu)造函數(shù)內(nèi) 又使用靜態(tài)變量bowl2 調(diào)用了其對象內(nèi)的方法,所以打印 f1(1) //到此這一行代碼執(zhí)行的初始化全部執(zhí)行完畢 static Table table = new Table(); //第2步: //初始化 Cupboard 類,因?yàn)?Cupboard 類中也含有兩個靜態(tài)對象,所以依次執(zhí)行 Bowl(4) 和 Bowl(5) //在執(zhí)行Cupboard構(gòu)造函數(shù)之前先執(zhí)行變量初始化的規(guī)則,所以 bowl3 先執(zhí)行,打印 Bolw(3) //然后執(zhí)行無參構(gòu)造函數(shù),打印 Cupboard() //到此,這行代碼的初始化全部執(zhí)行完畢 static Cupboard cupboard = new Cupboard(); }
執(zhí)行結(jié)果:
Bowl(1)Bowl(2)Table()f1(1)Bowl(4)Bowl(5)Bowl(3)Cupboard()Creating new Cupboard in mainBowl(3)Cupboard()Creating new Cupboard in mainBowl(3)Cupboard()f2(111)f3(111)
以上就是Java 靜態(tài)數(shù)據(jù)初始化的示例代碼的詳細(xì)內(nèi)容,更多關(guān)于Java 靜態(tài)數(shù)據(jù)初始化的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. Python如何批量生成和調(diào)用變量2. ASP.NET MVC實(shí)現(xiàn)橫向展示購物車3. ASP.Net Core對USB攝像頭進(jìn)行截圖4. .net如何優(yōu)雅的使用EFCore實(shí)例詳解5. ASP.Net Core(C#)創(chuàng)建Web站點(diǎn)的實(shí)現(xiàn)6. python 爬取京東指定商品評論并進(jìn)行情感分析7. python基礎(chǔ)之匿名函數(shù)詳解8. Python獲取B站粉絲數(shù)的示例代碼9. ajax動態(tài)加載json數(shù)據(jù)并詳細(xì)解析10. 通過CSS數(shù)學(xué)函數(shù)實(shí)現(xiàn)動畫特效
