/*
* 静态代码块
* 格式:
* static {
*
* 静态代码块中的执行语句
* }
* 特点:1,随着类的加载而执行,只执行一次,并优先于主函数执行
* 2,用于给类进行初始化
* */
public class StaticCodeDemo {
/**
* @param args
*/
static {
System.out.println("a");//第一
}
public static void main(String[] args) {
// TODO Auto-generated method stub
/* new StaticCode();//第三
new StaticCode();//不会再被执行 因为静态代码块随着类的加载而执行 只执行一次
System.out.println("OVER");//第四
StaticCode.show();//没有对象 直接调用 因为静态
*/
new StaticCode(5); //如果不付参数 则执行B
}
static {
System.out.println("b");//第二
}
}
class StaticCode
{
int num = 6;//如果不静态初始化 则不可访问num的值 除非有对象 对象可以调用该元素
StaticCode(){
System.out.println(“B”);
}
static {
System.out.println(“c”);//如果(“c”+num)此时num不可访问
}
{
System.out.println("C"+num);
}
StaticCode(int x){
System.out.println("F");
}
public static void show() {
// TODO Auto-generated method stub
System.out.println("run show");
}
}