public class Student {
<span style="white-space:pre"> </span>static{
<span style="white-space:pre"> </span>System.out.println("this is static block ");
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>{
<span style="white-space:pre"> </span>System.out.println("this is non-static block 1");
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>public Student(int id){
<span style="white-space:pre"> </span>System.out.println("student("+id+")");
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>public Student(){
<span style="white-space:pre"> </span>System.out.println("student()");
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>{
<span style="white-space:pre"> </span>System.out.println("this is non-static block 2");
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>public static void main(String[] args) {
<span style="white-space:pre"> </span>Student s1 = new Student(1);
<span style="white-space:pre"> </span>Student s2 = new Student(2);
<span style="white-space:pre"> </span>Student p = new Student();
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>
}
this is static block
this is non-static block 1
this is non-static block 2
student(1)
this is non-static block 1
this is non-static block 2
student(2)
this is non-static block 1
this is non-static block 2
student()
我们new了两个对象,可是静态块只执行了一次,而非静态块执行了两个,且都是在调用构造器之前。我们似乎得出了一些结论:静态块是在类的装载时执行的(装入.class文件后),且只执行一次。而非静态块是在调用构造方法之前执行的,每生成一个实例对象,就会调用一次非静态块。
public class Student {
public Student(int id) {
System.out.println("student(" + id + ")");
}
public Student(){
System.out.println("Student()");
}
public static void main(String[] args) {
BuildStudent buildStudent = new BuildStudent();
}
}
class BuildStudent {
Student s1 = new Student(1);
public BuildStudent() {
System.out.println("this is buildStudent's block!");
Student s2 = new Student(2);
}
Student s3 = new Student();
Student s4 = new Student(3);
}
student(1)
Student()
student(3)
this is buildStudent's block!
student(2)
不论变量放在哪儿,都会先于任意一个方法的执行前执行,包括构造方法,而构造方法是一个类必须会执行的方法,不需要显示的进行调用。同时,不论变量在哪儿分布,只要在方法外部,就一定先于方法初始化。