public class Student {
static int number = 80;
static String name;
//静态代码块
static{
System.out.println("静态代码块执行");
name = "BugMaker";
}
}
public class Test {
public static void main(String[] args) {
//四个语句
System.out.println(Student.number);
System.out.println(Student.number);
System.out.println(Student.number);
System.out.println(Student.number);
System.out.println(Student.name);
}
}
运行结果:
2、实例代码块
格式:{ }
特点:每次创建对象时,执行实例代码块,并在构造器前执行。
作用:和构造器一样,都是用来完成对象的初始化,例如对实例变量进行初始化赋值。
代码举例:
class Test2 {
public static void main(String[] args) {
Student2 student2 = new Student2();
System.out.println("=======================================================");
Student2 student21 = new Student2("BugMaker");
}
}
public class Student2 {
//实例代码块
{
System.out.println("实例代码块执行了!!");
System.out.println("又人创造了对象" + this);
}
public Student2(){
System.out.println("无参构造器执行了!!");
}
public Student2(String name){
System.out.println("有参构造器执行了!!");
}
}