问:写出下面程序片段的运行结果?
class Father {
{
System.out.println("FB0 ......");
}
static {
System.out.println("FSB0 ......");
//d\a无法在此打印,执行在此时d\a还位初始化
}
static int a = 1;
static {
System.out.println("FSB1 a:" + a);
//d无法在此打印,执行在此时d还位初始化
}
int b = 1;
static {
a++;
System.out.println("FSB2 a:" + a);
//d无法在此打印,执行在此时d还位初始化
}
final static int c = 1;
static {
System.out.println("FSB3 c:" + c);
//d无法在此打印,执行在此时d还位初始化
}
public Father() {
a++;
b++;
System.out.println("F CONSTTRUCTOR a:" + a + ", b:" + b + ", c:" + c + ", d:" + d);
}
{
a++;
b++;
System.out.println("FB4 a:" + a + ", b:" + b + ", c:" + c);
//d无法在此打印,执行在此时d还位初始化
}
final int d = 1;
public void func1() {
a++;
b++;
System.out.println("F func1 a:" + a + ", b:" + b + ", c:" + c + ", d:" + d);
}
public static void func2() {
a++;
System.out.println("F func2 a:" + a + ", c:" + c);
}
}
class Child extends Father {
{
System.out.println("CB0 ......");
}
static {
System.out.println("CSB0 ......");
//d\a无法在此打印,执行在此时d\a还位初始化
}
static int a = 1;
static {
System.out.println("CSB1 a:" + a);
//d无法在此打印,执行在此时d还位初始化
}
int b = 1;
static {
a++;
System.out.println("CSB2 a:" + a); //
// d无法在此打印,执行在此时d还位初始化
}
final static int c = 1;
static {
System.out.println("CSB3 c:" + c);
//d无法在此打印,执行在此时d还位初始化
}
public Child() {
a++;
b++;
System.out.println("C CONSTTRUCTOR a:" + a + ", b:" + b + ", c:" + c + ", d:" + d);
}
{
a++;
b++;
System.out.println("CB4 a:" + a + ", b:" + b + ", c:" + c);
//d无法在此打印,执行在此时d还位初始化
}
final int d = 1;
public void func1() {
a++;
b++;
System.out.println("C func1 a:" + a + ", b:" + b + ", c:" + c + ", d:" + d);
}
public static void func2() {
a++;
System.out.println("C func2 a:" + a + ", c:" + c);
}
public static class BBQ {
static {
System.out.println("BBQ");
}
}
}
public class Demo {
public static void main(String[] args) {
System.out.println("new Child3.BBQ():");
Child3.BBQ bbq = new Child3.BBQ();
System.out.println("Father3.func2():");
Father3.func2();
System.out.println("Child3.func2():");
Child3.func2();
System.out.println("new Child3():");
Father3 father = new Child3();
System.out.println("father.func1():");
father.func1();
}
}
答:此题考察类实例化初始化流程,所得结果如下:
new Child3.BBQ():
BBQ
Father3.func2():
FSB0 ......
FSB1 a:1
FSB2 a:2
FSB3 c:1
F func2 a:3, c:1
Child3.func2():
CSB0 ......
CSB1 a:1
CSB2 a:2
CSB3 c:1
C func2 a:3, c:1
new Child3():
FB0 ......
FB4 a:4, b:2, c:1
F CONSTTRUCTOR a:5, b:3, c:1, d:1
CB0 ......
CB4 a:4, b:2, c:1
C CONSTTRUCTOR a:5, b:3, c:1, d:1
father.func1():
C func1 a:6, b:4, c:1, d:1
静态初始化块只执行一次;
初始化类之后才会执行实例化块;