zaw*_*wdd 0 java initialization class
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: i=0 n=99t1
construct block
2: i=1 n=100t2
static construct block
construct block
1: i=0 n=101initl
Run Code Online (Sandbox Code Playgroud)
谁能告诉我它是如何工作的?为什么在创建t1和t2软件时没有"静态构造块"?为什么我和j改为默认值,但是n仍然不变?
静态变量/块在它们出现时(通常)执行/初始化.
你的输出,为什么?:
加载类并在初始化期间,将执行以下行
public static test t1 = new test("t1");
public static test t2 = new test("t2");
Run Code Online (Sandbox Code Playgroud)
它反过来创建新的Test对象,但由于该类已经初始化,因此上面的行不会再次执行.
所以,
你得到
construct block
1: i=0 n=99t1
construct block
2: i=1 n=100t2
Run Code Online (Sandbox Code Playgroud)
接下来,执行静态块
static construct block
Run Code Online (Sandbox Code Playgroud)
现在,当您创建Test in对象时main()
,您将拥有
construct block
1: i=0 n=101initl
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
87 次 |
最近记录: |