1.概念:JAVA中用{ }括起来的代码称为代码块。
2.分类:局部代码块,构造代码块,同步代码块
a.局部代码块:在方法中出现,限定变量生命周期,以及早释放,提高内存利用率。
1 public static void main(String[] args){ 2 { 3 int x = 10;4 } 5 System.out.println(x); //这里的x未被定义 6 }
b.构造代码块(初始化块):多个构造方法中相同的代码放到一起,每次调用构造都执行并且在构造方法前执行
public class day1 { public static void main(String[] args){ Person p1 = new Person(); Person p2 = new Person("Smart"); } } class Person{ String name; public Person(String name){ this.name = name; System.out.println("有参构造"); } public Person(){ System.out.println("空参构造"); } { System.out.println("构造代码块"); } } /*输出结果*/ 构造代码块 空参构造 构造代码块 有参构造
c.静态代码块:*在类中方法外出现,用于给类进行初始化,在加载时候就执行,并且只执行一次,一般用来加载驱动。
class Student {
public Student() {
System.out.println("Student 构造方法");
}
{
System.out.println("Student 构造代码块");
}
static {
System.out.println("Student 静态代码块"); //只执行一次
}
}
class day1 {
public static void main(String[] args) {
System.out.println("我是main方法");
Student s1 = new Student();
Student s2 = new Student();
}
static {
System.out.println("day1静态代码块");
}
}
/*优先级*/
主函数中 静态代码块>main函数
成员函数中 静态代码块>构造代码块
/*输出结果*/
day1静态代码块
我是main方法
静态代码块
构造代码块
Student 构造方法
Student 构造代码块
Student 构造方法