靜態代碼塊,在類中方法外,隨着類的加載而加載,與建立對象的次數無關,只執行一次。this
構造代碼塊,在類中方法外,隨着對象的建立執行,建立多少對象執行多少次。spa
class Student{對象
public Student(){class
system.out.println("空參構造");方法
}static
public Student(String name,int age){co
this.name=name;background
this.age=age;new
system.out.println("有參構造");
}
{
system.out.println("構造代碼塊");
}
static{
system.out.println("靜態代碼塊");
}
主方法中
Student s1 = new Student();
Student s2 = new Student("xy",5);
輸出結果爲
靜態代碼塊
構造代碼塊
空參構造
構造代碼塊
有參構造