privatestaticTestStaticCodetsc=newTestStaticCode();--1
static{--2
System.out.println("4");
}
同样的static级别,会按顺序执行,所以先执行--1后执行--2
执行--1的时候,应为newTestStaticCode();会生成TestStaticCode实例,所以会先调用TestStaticCode的初始化块代码,然后再调用构造方法
privateInstanceVariableiv=newInstanceVariable();
这条语句相当于2条语句
privateInstanceVariableiv;
{iv=newInstanceVariable();}
其他的就不用说明了,static{}静态块在类加载的时候被调用,{}非静态初始化块在实例对象被初始化构造方法被调用之前被调用
举个例子,LZ理解好这个例子就能理解你的代码了
publicclassTest{
publicTest(){
System.out.println("我是构造方法9");
System.out.println("我是构造方法10");
}
{System.out.println("我是非静态初始化块5");}
{System.out.println("我是非静态初始化块6");}
Stringstr2="我是静态代码块7";
{
System.out.println(str2);
str2="我是静态代码块8";
System.out.println(str2);
}
static{System.out.println("我是静态代码块1");}
static{System.out.println("我是静态代码块2");}
staticStringstr="我是静态代码块3";
static{
System.out.println(str);
str="我是静态代码块4";
System.out.println(str);
}
publicstaticvoidmain(String[]args){
newTest();
}
}