何时初始化静态字段?如果我从不实例化一个类,但是我访问一个静态字段,是否所有静态块和私有静态方法用于实例化那个时刻调用的私有静态字段(按顺序)?
如果我调用静态方法怎么办?它是否也运行所有静态块?方法之前?
package ali;
public class test {
public static int n = 99;
public static test t1 = new test("t1");
public static test t2 = new test("t2");
public static int i = 0;
public static int j = i;
{
System.out.println("construct block");
}
static {
System.out.println("static construct block");
}
public test(String str){
System.out.println((++j) + ":" + " i="+ i + " n="+n+str);
n++;i++;
}
public static void main(String [] args){
test test1 = new test("initl");
}
}
Run Code Online (Sandbox Code Playgroud)
跑完后:
construct block
1: …
Run Code Online (Sandbox Code Playgroud)