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 时没有“静态构造 block ”? 为什么i和j都改成默认的了,n却没变?
最佳答案
静态变量/ block 在出现时执行/初始化(通常)。
你的输出以及为什么? :
当类加载并初始化期间,将执行以下几行
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
接下来,静态 block 执行
static construct block
现在,当您在 main()
中创建 Test 对象时,您将拥有
construct block
1: i=0 n=101initl
关于java类的初始化顺序,它是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25562443/