java靜態代碼塊

http://www.54xue.com/viewnews-4863.html
Java代碼  收藏代碼
  1. public class Test5 {   
  2. private static int a;   
  3. private int b;   
  4.   
  5. static{   
  6. Test5.a=3;   
  7. System.out.println(a);   
  8. Test5 t=new Test5();   
  9. t.f();   
  10. t.b=1000;   
  11. System.out.println(t.b);   
  12. }   
  13. static{   
  14. Test5.a=4;   
  15. System.out.println(a);   
  16. }   
  17. public static void main(String[] args) {   
  18. }   
  19. static{   
  20. Test5.a=5;   
  21. System.out.println(a);   
  22. }   
  23. public void f(){   
  24. System.out.println("hhahhahah");   
  25. }   
  26. }   



運行結果:
3
hhahhahah
1000
4
5
分析:
static 代碼塊也叫靜態代碼塊,是在類中獨立於類成員的static語句塊,可以有多個,位置可以隨便放,它不在任何的方法體內,JVM加載類時會執行這些靜態的 代碼塊,如果static代碼塊有多個,JVM將按照它們在類中出現的先後順序依次執行它們,每個代碼塊只會被執行一次 ( 我記得藍色之路里就有這麼一道類似的變態題目)

-------------------------------------------------------------
http://yahaitt.iteye.com/blog/143457
靜態代碼塊的執行順序
補充:


在有類內非靜態代碼塊的情況下,執行順序應該如下:

靜態代碼塊的執行順序:

1.父類的靜態代碼塊

2.子類的靜態代碼塊

3.父類的非靜態代碼塊

4.父類的構造函數

5.子類的非靜態代碼塊

6.子類的構造函數
================================================
Java代碼  收藏代碼
  1. //靜態代碼塊的執行順序  
  2.   
  3.    
  4. import static java.lang.System.out;  
  5.   
  6. class Bird  
  7. {  
  8.       
  9.       
  10.     public Bird()  
  11.     {  
  12.         out.print("b2 ");  
  13.     }  
  14.       
  15.     {out.print("b1 ");}  
  16.       
  17.     static   
  18.     {  
  19.         out.print("bs0 ");  
  20.     }  
  21. }  
  22.   
  23. class Raptor extends Bird  
  24. {  
  25.     static   
  26.     {  
  27.         out.print("rs1 ");  
  28.     }  
  29.       
  30.     public Raptor()  
  31.     {  
  32.         out.print("r2 ");  
  33.     }  
  34.       
  35.     {  
  36.         out.print("r3 ");  
  37.     }  
  38.       
  39.     static  
  40.     {  
  41.         out.print("rs4 ");  
  42.     }  
  43. }  
  44.   
  45. public class G015 extends Raptor{  
  46.     public static void main(String[] args) {  
  47.         out.print("pre ");  
  48.         new G015();  
  49.         out.println("G015  ");  
  50.     }  
  51.   
  52. }  


輸出結果應爲:
bs0 rs1 rs4 pre b1 b2 r3 r2 G015 
發佈了1 篇原創文章 · 獲贊 1 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章