
代碼塊
1:普通代碼塊:直接定義在方法中的代碼
public class MainDemo01 { public static void main(String args[]){ { int c = 40; System.out.println(c); } int c =100; System.out.println(c); } }
輸出為:
F:\java>javac MainDemo01.java
F:\java>java MainDemo01 one
40
100
2:構(gòu)造代碼塊:直接定義在類中的代碼
class Demo { { System.out.println("構(gòu)造塊"); } public Demo(){ System.out.println("構(gòu)造方法"); } } public class MainDemo01 { public static void main(String args[]){ new Demo(); new Demo(); new Demo(); new Demo(); new Demo(); } }
輸出為:
F:\java>java MainDemo01
構(gòu)造塊
構(gòu)造方法
構(gòu)造塊
構(gòu)造方法
構(gòu)造塊
構(gòu)造方法
構(gòu)造塊
構(gòu)造方法
構(gòu)造塊
構(gòu)造方法
構(gòu)造塊優(yōu)于構(gòu)造方法執(zhí)行,執(zhí)行多次。
3:靜態(tài)代碼塊:直接使用static關(guān)鍵字聲明的代碼
class Demo { { System.out.println("構(gòu)造塊"); } static { System.out.println("靜態(tài)代碼塊"); } public Demo(){ System.out.println("構(gòu)造方法"); } } public class MainDemo01 { static{ System.out.println("在主方法中定義的代碼塊"); } public static void main(String args[]){ new Demo(); new Demo(); new Demo(); new Demo(); new Demo(); } }
輸出為:
F:\java>java MainDemo01
在主方法中定義的代碼塊
靜態(tài)代碼塊
構(gòu)造塊
構(gòu)造方法
構(gòu)造塊
構(gòu)造方法
構(gòu)造塊
構(gòu)造方法
構(gòu)造塊
構(gòu)造方法
構(gòu)造塊
構(gòu)造方法
得出結(jié)論;
1:靜態(tài)塊優(yōu)先于主方法執(zhí)行,如果在普通類中定義的靜態(tài)塊,優(yōu)先于構(gòu)造塊執(zhí)行,不管有多少實(shí)例化對(duì)象產(chǎn)生,靜態(tài)代碼塊只執(zhí)行一次,靜態(tài)代碼塊的主要功能是為靜態(tài)屬性初始化。
能不能不使用主方法就輸出“helloworld”呢?
答案是可以的。
public class MainDemo01 { static{ System.out.println("helloworld"); } }
輸出為:
F:\java>java MainDemo01
helloworld
Exception in thread "main" java.lang.NoSuchMethodError: main
可以輸出,但是出現(xiàn)錯(cuò)誤,程序仍然繼續(xù)尋找主方法,能不能去掉這個(gè)錯(cuò)誤呢》
答案是可以的
public class MainDemo01 { static{ System.out.println("helloworld"); System.exit(1); } }
輸出為:
F:\java>java MainDemo01
helloworld
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長非常感激您!手機(jī)微信長按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元
