javacMainDemo01.javaF:\java>javaMainDemo01one401002:構(gòu)造代碼塊:直接定義在類中的代碼classD" />

日韩久久久精品,亚洲精品久久久久久久久久久,亚洲欧美一区二区三区国产精品 ,一区二区福利

java學(xué)習(xí)筆記(十八)代碼塊

系統(tǒng) 2082 0
java學(xué)習(xí)筆記(十八)代碼塊

代碼塊

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í)行,不管有多少實例化對象產(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)錯誤,程序仍然繼續(xù)尋找主方法,能不能去掉這個錯誤呢》

答案是可以的


    public class MainDemo01
{
 static{
 System.out.println("helloworld");
 System.exit(1);
 }
}

  



輸出為:


F:\java>java MainDemo01
helloworld

java學(xué)習(xí)筆記(十八)代碼塊


更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主

微信掃碼或搜索:z360901061

微信掃一掃加我為好友

QQ號聯(lián)系: 360901061

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。

【本文對您有幫助就好】

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描上面二維碼支持博主2元、5元、10元、自定義金額等您想捐的金額吧,站長會非常 感謝您的哦!!!

發(fā)表我的評論
最新評論 總共0條評論
主站蜘蛛池模板: 石首市| 东乡县| 江西省| 乳山市| 张北县| 鹿泉市| 阳曲县| 崇明县| 即墨市| 宜兴市| 波密县| 平江县| 阿鲁科尔沁旗| 江陵县| 福贡县| 襄樊市| 通城县| 桦甸市| 天峨县| 东乌珠穆沁旗| 小金县| 昌平区| 鹤岗市| 宜黄县| 扬州市| 新密市| 上林县| 临沧市| 无锡市| 旅游| 盖州市| 龙胜| 抚松县| 类乌齐县| 塔城市| 米林县| 沂源县| 乐亭县| 琼海市| 张家川| 珠海市|