今天写类测试了其中代码块的运行和static运行时机:
public class StaticClass {
public static int j=8;
static{
j=9;
System.out.println("j="+j+",in staic zone");
}
public StaticClass(){
j=10;
System.out.println("j="+j+",in the constructor");
}
{
j=11;
System.out.println("j="+j+",in the ordinary code zone");
}
}
public class test {
public static void main(String []args){
System.out.println("Hello world");
StaticClass sc;
}
}
运行结果:
Hello world
</pre><pre name="code" class="java">public class test {
public static void main(String []args){
System.out.println("Hello world");
StaticClass sc=new StaticClass();
}
}
运行结果:
Hello world
j=9,in staic zone
j=11,in the ordinary code zone
j=10,in the constructor
结论:1,类中的static代码块只是在,当类被载入时被执行,且只被执行一次,静态块常用来执行类属性的初始化。使用new创建新对象时,会去加载类。
2,类中各部分执行顺序是:static代码块-->非static代码块-->构造函数
Java小菜,若有不对之处,请指教。