(1)静态块
静态块指的是由static关键字定义的代码块,必须分为2种情况考虑静态块:
~在非主类中定义的静态块
~在主类中定义的静态块


public class Test {


public static void main(String[] args) {
new Person();
new Person();



}


}
class Person
{   private static String info="hellow";
{
System.out.println("1,Person类的构造块");

}
public Person()
{
System.out.println("2,Person类的构造方法");
}


static{//静态块
info+="world";
System.out.println("3,Person类的静态块"+info);
}


}
结果:
3,Person类的静态块hellowworld
1,Person类的构造块
2,Person类的构造方法
1,Person类的构造块
2,Person类的构造方法


总结:静态块优先于构造块执行,静态块只使用一次,其最主要的作用是为static属性初始化。


示例2:静态块也可以定义在主类中,此时的静态块将优先于主方法。




public class Test {


public static void main(String[] args) {
System.out.println("sdru");


}
static {

System.out.println("--------------");
}


}
结果:
--------------
sdru


本文转载:CSDN博客