代碼塊:在Java中,使用{}括起來的代碼被稱為代碼塊。
根據其位置和聲明的不同,可以分為:
局部代碼塊:局部位置,用于限定變量的生命周期。
構造代碼塊:在類中的成員位置,用{}括起來的代碼。每次調用構造方法執行前,都會先執行構造代碼塊。作用:可以把多個構造方法中的共同代碼放到一起,對對象進行初始化。
靜態代碼塊:在類中的成員位置,用{}括起來的代碼,只不過它用static修飾了。作用:一般是對類進行初始化。
相關面試題:
靜態代碼塊,構造代碼塊,構造方法的執行順序?
靜態代碼塊 --> 構造代碼塊 --> 構造方法
靜態代碼塊:只執行一次
構造代碼塊:每次調用構造方法都執行
class Student {static {System.out.println("Student 靜態代碼塊");}{System.out.println("Student 構造代碼塊");}public Student() {System.out.println("Student 構造方法");}
}class StudentDemo {static {System.out.println("StudentDemo 靜態代碼塊");}public static void main(String[] args) {System.out.println("這是main方法");Student s1 = new Student();Student s2 = new Student();}
}
上述程序執行結果為:
StudentDemo 靜態代碼塊
這是main方法
Student 靜態代碼塊
Student 構造代碼塊
Student 構造方法
Student 構造代碼塊
Student 構造方法