java类初始化命令,它是如何工作的?

时间:2014-08-29 05:58:02

标签: java class initialization

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");
}
}
跑完后

construct block
1:  i=0  n=99t1
construct block
2:  i=1  n=100t2
static construct block
construct block
1:  i=0  n=101initl

谁能告诉我它是如何运作的? 为什么没有"静态构造块"什么时候创建t1和t2? 为什么我和j改为默认值,但是n仍然不变?

2 个答案:

答案 0 :(得分:5)

静态变量/块在出现时(通常)执行/初始化。

你的输出,为什么? :

当加载类并在初始化期间,将执行以下行

public static test t1 = new test("t1");
public static test t2 = new test("t2");

反过来创建新的Test对象,但由于该类已经在初始化,因此上述行不会再次执行。

所以,

你得到了

construct block
1:  i=0  n=99t1
construct block
2:  i=1  n=100t2

接下来,静态块执行

static construct block

现在,当您在main()中创建一个Test对象时,您将拥有

construct block
1:  i=0  n=101initl

答案 1 :(得分:2)

当加载此类(实际上应具有大写名称)时,将按照它们在源代码中出现的顺序调用静态初始值设定项。这意味着new test("t?")对象创建发生在显式静态块之前。