class StaticCode{
//静态代码块
static {
System.out.println("static code......");
}
void show(){
System.out.println("show static code......");
}
}
class StaticCodeDemo{
public static void main(String[] args){
//只会打印一次静态代码块的内容
new StaticCode().show();
new StaticCode().show();
}
}
/*
静态代码块随着类的加载而执行,且执行一次
作用:用于给类进行初始化
*/
class StaticCode{
static int n;
static {
n=10;
n+=2;
System.out.println("static code......");
}
static void show(){
System.out.println("n="+n);
}
}
class StaticCodeDemo{
public static void main(String[] args){
//new StaticCode().show();
//new StaticCode().show();
StaticCode.show();//不需要new对象了
}
}
当一些类中全部是静态成员时,就不需要构造对象了,这个时候可以使用static代码块,随着该类的使用,可以在static代码块中初始化静态成员(也可以直接赋值,static int n=10,但是这样就固定死了静态变量的值,在静态代码块中可以去对静态变量做一些操作)