java中的代码块理解

代码块:就是用{}括起来到部分。根据应用的不同分为4类:普通代码块、构造块、静态代码块、同步代码块。

1.普通代码块:定义在方法中的代码块。

如:


  1. publicclass Ex22 {    

  2. publicstaticvoid main(String[] args){    

  3. //      普通代码块  

  4.        {    

  5. int i = 3;    

  6.            System.out.println("局部变量为 " + i);    

  7.        }    

  8. int i = 5;    

  9.        System.out.println("相对上面的  i 来说是全局的变量 " + i);    

  10.    }    

  11. }    

  12. //局部变量为 3  

  13. //相对上面的  i 来说是全局的变量 5


2.构造块:直接在类中编写的代码块。


  1. class Demo5{    

  2.    {    

  3.        System.out.println("构造块");    

  4.    }    

  5. public Demo5(){    

  6.        System.out.println("构造方法");    

  7.    }    

  8.    {    

  9.        System.out.println("构造方法后的构造块");    

  10.    }    

  11. }    

  12. publicclass Ex22 {    

  13. publicstaticvoid main(String[] args){    

  14. new Demo5();    

  15. new Demo5();    

  16.    }    

  17. }    

  18. //构造块  

  19. //构造方法后的构造块  

  20. //构造方法  

  21. //构造块  

  22. //构造方法后的构造块  

  23. //构造方法  


对象被实例化一次构造块就执行一次;

构造块优先执行比构造方法.

3.静态代码块:static 关键字声明的代码块.


  1. class Demo5{    

  2.    {    

  3.        System.out.println("1构造块");    

  4.    }    

  5. public Demo5(){    

  6.        System.out.println("2构造方法");    

  7.    }    

  8.    {    

  9.        System.out.println("3构造方法后的构造块");    

  10.    }    

  11. static {    

  12.        System.out.println("4静态代码块");    

  13.    }    

  14. }    

  15. publicclass Ex22 {    

  16. static {    

  17.        System.out.println("在主方法类中定义的代码块");    

  18.    }    

  19. publicstaticvoid main(String[] args){    

  20. new Demo5();    

  21. new Demo5();    

  22.    }    

  23. }    

  24. //在主方法类中定义的代码块  

  25. //4静态代码块  

  26. //1构造块  

  27. //3构造方法后的构造块  

  28. //2构造方法  

  29. //1构造块  

  30. //3构造方法后的构造块  

  31. //2构造方法


主方法静态代码块优先于主方法,

在普通类中静态块优先于构造块,

在普通类中构造块优先于构造方法,

静态块只实例化一次。


参考:http://blog.csdn.net/lichaohn/article/details/5359240

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章