簡述
- static{} 靜態代碼塊,加載類之前執行
- {} 代碼塊,每次new的時候都會被執行
示例
類:
public class Student {
int age;
String name;
boolean sex;
public Student(){
age=10;
name="Xu";
sex=false;
}
static{
System.out.println("This is a static block");
}
{
System.out.println("這是一個代碼塊");
}
}
調用函數:
public class Student_test {
public static void main(String[] args) {
Student student1= new Student();
Student student2= new Student();
Student student3= new Student();
Student student4= new Student();
}
}
輸出結果:
This is a static block
這是一個代碼塊
這是一個代碼塊
這是一個代碼塊
這是一個代碼塊
創建了4個對象,但是static塊只執行一次,而代碼塊,每次創建對象,都會被執行。