13 代码块

代码块是指使用“{}”括起来的一段代码,根据位置不同,代码块可以分为四种:普通代码块,构造块,静态代码块,同步代码块

 

普通代码块:直接定义在方法中的代码块称为普通代码块

 1 public class CodeDemo01{
 2     public static void main(String args[]){
 3         {        // 普通代码块
 4             int x = 30 ;    // 就属于一个局部变量
 5             System.out.println("普通代码块 --> x = " + x) ;
 6         }
 7         int x = 100 ;        // 与局部变量名称相同
 8         System.out.println("代码块之外 --> x = " + x) ;
 9     }
10 };
View Code

 

构造块:将代码块直接定义在类中的称为构造块 (构造块优先于构造方法执行,且执行多次。只要一有实例化对象产生,就执行构造块中的内容)

 1 class Demo{
 2     {    // 直接在类中编写代码块,称为构造块
 3         System.out.println("1、构造块。") ;
 4     }
 5     public Demo(){    // 定义构造方法
 6         System.out.println("2、构造方法。") ;
 7     }
 8 };
 9 public class CodeDemo02{
10     public static void main(String args[]){
11         new Demo() ;        // 实例化对象
12         new Demo() ;        // 实例化对象
13         new Demo() ;        // 实例化对象
14     }
15 };
View Code

 

静态代码块:直接使用static关键字声明的代码块称为静态代码块(静态代码块优先于主方法执行,如果在普通类中定义的静态块,优先于构造块执行,不管有多少个实例化对象产生,静态代码块的主要功能就是为静态属性初始化)

public class Test{
    {    // 直接在类中编写代码块,称为构造块
        System.out.println("主类的构造块。") ;
    }
    static{        // 在主方法所在的类中定义静态块
        System.out.println("在主方法所在类中定义的代码块") ;
    }
    public static void main(String args[]){
        new DDemo() ;        // 实例化对象
        new DDemo() ;        // 实例化对象
        new DDemo() ;        // 实例化对象
    }
}
class DDemo{
    {    // 直接在类中编写代码块,称为构造块
        System.out.println("1、构造块。") ;
    }
    static{    // 使用static,称为静态代码块
        System.out.println("0、静态代码块") ;
    }
    public DDemo(){    // 定义构造方法
        System.out.println("2、构造方法。") ;
    }
}
View Code

注:静态代码块在类加载时执行,构造块在对象初始化时执行。(为什么主类的构造块没执行的原因)

posted @ 2015-02-26 10:37  闲来垂钓  阅读(130)  评论(0)    收藏  举报