静态代码块 非静态代码块和构造函数执行顺序

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()
{
a = 30;
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
30
30
30

当我们在使用B类时,JVM将B的定义装载,这时它调用了B的静态定义初始化和静态代码块 由于是静态的,尽管我们打印了两次,静态定义初始化和静态代码块都只执行了一次。构造函数是后于非静态代码块执行的.
在屏蔽了Class B中的main方法后,我们再写一个C类继承B类,如下:
class C extends B
{
static int c = 0;
static
{
c = 10;
System.out.println("C.static code is runnning and now c is " + c);

}
{
c = 20;
System.out.println("C.non-static code is runnning and now c is " + c);

}

public C()
{
c = 30;
System.out.println("C.constructor is running and now c is " + c);
}
public static void main(String args[])
{
System.out.println(C.c);
System.out.println(C.c);
C c1 = new C();
C c2 = new C();
System.out.println(c1.c);
System.out.println(c2.c);
System.out.println(C.c);

}
}

B.static scope is running
C.static code is runnning and now c is 10
10
10
B.scope is running
B.Constructor is running
C.non-static code is runnning and now c is 20
C.constructor is running and now c is 30
B.scope is running
B.Constructor is running
C.non-static code is runnning and now c is 20
C.constructor is running and now c is 30
30
30
30

在此描述一下c变化过程,虽然定义了两个对象c1,c2但其实只有一份共有的c,c被装载时先被初始化为0,后来执行静态代码块时被初始化为10,接着执行c1的非静态代码快时被初始化为20,然后是c1的构造函数被出化为30,然后轮到c2的非静态代码块,这是又重新被初始化回20,然后c2的构造函数,变为30.

你可能感兴趣的:(静态代码块 非静态代码块和构造函数执行顺序)