本帖最后由 杜佳瑞 于 2012-7-27 23:06 编辑
网上看到的变量,初始化块,构造函数的初始化顺序,看完后这类题就噢啦
网址http://blog.csdn.net/macheng365/article/details/6403050
class A{
private int i = 9;
protected static int j;
static{
System.out.println("-- Load First SuperClass of static block start!-- ");
System.out.println("j = " + j);
System.out.println("-- Load First SuperClass of static block End -- ");
}
public A(){
System.out.println("------- Load SuperClass of structor start --------");
System.out.println("Frist print j = " + j);
j = 10;
m();
System.out.println("k = " + k);
System.out.println("Second print j = " + j);
System.out.println("----------- Load SuperClass End ----------- ");
}
private static int k = getInt();
public static int getInt(){
System.out.println("Load SuperClass.getInt() ");
return 11;
}
static{
System.out.println("--- Load Second SuperClass of static block!-------");
System.out.println("j = " + j);
System.out.println("k = " + k);
System.out.println("-- Load Second SuperClass of static block End -- ");
}
public void m(){
System.out.println("SuperClass.m() , " + "j = " +j);
}
}
class B extends A {
private int a = 10;
static{
System.out.println("---- Load SubClass of static block!------");
System.out.println("-- Load SubClass of static block End -- ");
}
public B(){
System.out.println("Load SubClass of structor");
m();
System.out.println("--- Load SubClass End ---- ");
}
public void m(){
System.out.println("SubClass.m() ," + "a = " + a );
}
}
public class Test1{
public static void main(String[] args)
{
A a = new B();
}
}
正确的答案为:
-- Load First SuperClass of static block start!--
j = 0
-- Load First SuperClass of static block End --
Load SuperClass.getInt()
--- Load Second SuperClass of static block!-------
j = 0
k = 11
-- Load Second SuperClass of static block End --
---- Load SubClass of static block!------
-- Load SubClass of static block End --
------- Load SuperClass of structor start --------
Frist print j = 0
SubClass.m() ,a = 0
k = 11
Second print j = 10
----------- Load SuperClass End -----------
Load SubClass of structor
SubClass.m() ,a = 10
--- Load SubClass End ----
|
|