代码块顾名思义就是就是用{}括起来到部分的一块代码。根据应用的不同分为4类:普通代码块、构造块、静态代码块、同步代码块。在平常开发中用的可能并不是很多,在写上面几篇博客的时候提到过这个问题,今天就在这写一下。对于代码块的问题,我认为重要的就是搞清楚代码块和方法中代码的执行顺序问题就好了。
下面通过几段代码来说一下:
class B {
//静态变量
static int a = 0;
//非静态代码块
{
System.out.println("B.scope is running");
a = 10 ;
}
//静态代码块
static {
System.out.println("B.static scope is running");
a = 20;
}
//构造函数
public B() {
System.out.println("B.Constructor is running");
}
public static void main(String arg[]) {
System.out.println(B.a);
System.out.println(B.a);
B b1 = new B();
B b2 = new B();
System.out.println(b1.a);
System.out.println(b2.a);
System.out.println(B.a);
}
}
输出结果如下:
B.static scope is running
20
20
B.scope is running
B.Constructor is running
B.scope is running
B.Constructor is running
10
10
10
通过上面的代码和执行后的结果我们不难看出其执行顺序,首先代码块的优先级是要高于构造函数的,静态的代码块又要高于非静态的代码块,因为静态的都是类的,JVM上首先要执行的就是这些静态的,然后才是其他的实例变量,静态代码和实例变量的初始化是在同一个等级的。