1、普通代码块
public class CodeDemo01{
public static void main(String args[]){
{ // 普通代码块
int x = 30 ; // 就属于一个局部变量
System.out.println("普通代码块 --> x = " + x) ;
}
//int x = 100 ; // 与局部变量名称相同
System.out.println("代码块之外 --> x = " + x) ;
}
};
代码块之外,引用变量x会报错。局部变量的作用域。
2、构造块
将代码块直接定义在类中,称为构造块。
class Demo{
{ // 直接在类中编写代码块,称为构造块
System.out.println("1、构造块。") ;
}
public Demo(){ // 定义构造方法
System.out.println("2、构造方法。") ;
}
};
public class CodeDemo02{
public static void main(String args[]){
new Demo() ; // 实例化对象
new Demo() ; // 实例化对象
new Demo() ; // 实例化对象
}
};
构造块优先于构造方法执行,且执行多次,只要一有实例化对象产生,就执行构造块中的内容。
3、静态代码块
使用static关键字声明的代码块, 为静态代码块。
class Demo{
{ // 直接在类中编写代码块,称为构造块
System.out.println("1、构造块。") ;
}
static{ // 使用static,称为静态代码块
System.out.println("0、静态代码块") ;
}
public Demo(){ // 定义构造方法
System.out.println("2、构造方法。") ;
}
};
public class CodeDemo03{
static{ // 在主方法所在的类中定义静态块
System.out.println("在主方法所在类中定义的代码块") ;
}
public static void main(String args[]){
new Demo() ; // 实例化对象
new Demo() ; // 实例化对象
new Demo() ; // 实例化对象
}
};
静态代码块优先于主方法执行,普通类中定义的静态块优先于构造方法执行。不管有多少个实例化对象产生,静态代码块只执行一次。
静态代码块的作用:主要就是为静态属性初始化。