小男孩‘自慰网亚洲一区二区,亚洲一级在线播放毛片,亚洲中文字幕av每天更新,黄aⅴ永久免费无码,91成人午夜在线精品,色网站免费在线观看,亚洲欧洲wwwww在线观看

分享

靜態(tài)代碼塊、非靜態(tài)代碼塊、構(gòu)造函數(shù)的執(zhí)行順序

 李副營(yíng)長(zhǎng) 2013-04-19
之前被面試問到父子類靜態(tài)代碼塊、非靜態(tài)代碼塊、構(gòu)造函數(shù) 
一直以來我我認(rèn)為這三者的執(zhí)行順序是靜態(tài)代碼塊、非靜態(tài)代碼塊、構(gòu)造函數(shù)。 
網(wǎng)上搜了下也都是這么說的。 
就像下面這段代碼: 
Java代碼  收藏代碼
  1. public class ExA {  
  2.     static {  
  3.         System.out.println("父類--靜態(tài)代碼塊");  
  4.     }  
  5.   
  6.     public ExA() {  
  7.         System.out.println("父類--構(gòu)造函數(shù)");  
  8.     }  
  9.   
  10.     {  
  11.         System.out.println("父類--非靜態(tài)代碼塊");  
  12.     }  
  13.   
  14.     public static void main(String[] args) {  
  15.         new ExB();  
  16.     }  
  17. }  
  18.   
  19. class ExB extends ExA {  
  20.     static {  
  21.         System.out.println("子類--靜態(tài)代碼塊");  
  22.     }  
  23.     {  
  24.         System.out.println("子類--非靜態(tài)代碼塊");  
  25.     }  
  26.   
  27.     public ExB() {  
  28.         System.out.println("子類--構(gòu)造函數(shù)");  
  29.     }  
  30. }  

執(zhí)行結(jié)果 
===== 
父類--靜態(tài)代碼塊 
子類--靜態(tài)代碼塊 
父類--非靜態(tài)代碼塊 
父類--構(gòu)造函數(shù) 
子類--非靜態(tài)代碼塊 
子類--構(gòu)造函數(shù) 

可是靜態(tài)代碼塊真的會(huì)一定在非靜態(tài)代碼塊之前執(zhí)行嗎? 
下面這段代碼 
Java代碼  收藏代碼
  1. public class ExA {  
  2.     private static ExA a = new ExA();  
  3.     static {  
  4.         System.out.println("父類--靜態(tài)代碼塊");  
  5.     }  
  6.   
  7.     public ExA() {  
  8.         System.out.println("父類--構(gòu)造函數(shù)");  
  9.     }  
  10.   
  11.     {  
  12.         System.out.println("父類--非靜態(tài)代碼塊");  
  13.     }  
  14.   
  15.     public static void main(String[] args) {  
  16.         new ExB();  
  17.     }  
  18. }  
  19.   
  20. class ExB extends ExA {  
  21.     private static ExB b = new ExB();  
  22.     static {  
  23.         System.out.println("子類--靜態(tài)代碼塊");  
  24.     }  
  25.     {  
  26.         System.out.println("子類--非靜態(tài)代碼塊");  
  27.     }  
  28.   
  29.     public ExB() {  
  30.         System.out.println("子類--構(gòu)造函數(shù)");  
  31.     }  
  32. }  

執(zhí)行結(jié)果 
===== 
父類--非靜態(tài)代碼塊 
父類--構(gòu)造函數(shù) 
父類--靜態(tài)代碼塊 
父類--非靜態(tài)代碼塊 
父類--構(gòu)造函數(shù) 
子類--非靜態(tài)代碼塊 
子類--構(gòu)造函數(shù) 
子類--靜態(tài)代碼塊 
父類--非靜態(tài)代碼塊 
父類--構(gòu)造函數(shù) 
子類--非靜態(tài)代碼塊 
子類--構(gòu)造函數(shù) 
===== 
可以發(fā)現(xiàn)非靜態(tài)代碼塊并不是一定在靜態(tài)代碼塊之后執(zhí)行的。 
我認(rèn)為此時(shí)private static ExA a = new ExA()是靜態(tài)變量。而java里面靜態(tài)變量與靜態(tài)代碼塊是按代碼先后順序執(zhí)行。所以就導(dǎo)致非靜態(tài)代碼塊在靜態(tài)代碼塊之前執(zhí)行。 

    本站是提供個(gè)人知識(shí)管理的網(wǎng)絡(luò)存儲(chǔ)空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請(qǐng)注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購(gòu)買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊一鍵舉報(bào)。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評(píng)論

    發(fā)表

    請(qǐng)遵守用戶 評(píng)論公約

    類似文章 更多