2019-07-16 09:36:07 7351瀏覽
今天千鋒扣丁學(xué)堂Java培訓(xùn)老師給大家分享一篇關(guān)于Java面試題static關(guān)鍵字的詳細(xì)介紹,文中通過示例代碼介紹的非常詳細(xì),下面我們一起來看一下吧。
package com.ant.param; public class StaticFieldDemo { public static void main(String[] args) { Foo f1 = new Foo(); Foo f2 = new Foo(); Foo f3 = new Foo(); System.out.println(f1.id + " " + f2.id + " " + f3.id ); } } class Foo{ int id; }
上面的代碼我們很熟悉,根據(jù)Foo構(gòu)造出的每一個(gè)對(duì)象都是獨(dú)立存在的,保存有自己獨(dú)立的成員變量,相互不會(huì)影響,他們?cè)趦?nèi)存中的示意如下:
package com.ant.param; public class StaticFieldDemo { public static void main(String[] args) { Foo f1 = new Foo(); Foo f2 = new Foo(); Foo f3 = new Foo(); System.out.println(f1.id + " " + f2.id + " " + f3.id + " " + Foo.i); } } class Foo{ int id; static int i=0; public Foo(){ id = i++; } } 運(yùn)行結(jié)果如下: 0 1 2 3
程序執(zhí)行過程內(nèi)存圖如下所示:
第2步:繼續(xù)加載類
第3步:繼續(xù)加載類
package com.ant.param; public class StaticFieldDemo { private static void print(){ System.out.println("hello"); } public static void main(String[] args) { StaticFieldDemo.print(); } }
package com.ant.param; public class StaticBlockDemo { public static void main(String[] args) { Foo foo = new Foo(); } } class Foo{ //代碼塊,在創(chuàng)建對(duì)象的時(shí)候執(zhí)行,使用很少,和構(gòu)造器差不多 { System.out.println("創(chuàng)建對(duì)象了!"); } //靜態(tài)代碼塊,在類加載期間執(zhí)行,用于加載配置文件或者其他信息等 static{ System.out.println("類加載了!"); } public Foo(){ System.out.println("調(diào)用了構(gòu)造器!"); } }
【關(guān)注微信公眾號(hào)獲取更多學(xué)習(xí)資料】 【掃碼進(jìn)入JavaEE/微服務(wù)VIP免費(fèi)公開課】
查看更多關(guān)于“Java開發(fā)資訊”的相關(guān)文章>>