代碼塊
在Java中,使用{}括起來的代碼被稱爲代碼塊。
- a:局部代碼塊
- 在方法中出現;限定變量生命週期,及早釋放,提高內存利用率
- b:構造代碼塊 (初始化塊)
- 在類中方法外出現;多個構造方法方法中相同的代碼存放到一起,每次調用構造都執行,並且在構造方法前執行
- c:靜態代碼塊
- 在類中方法外出現,並加上static修飾;用於給類進行初始化,在加載的時候就執行,並且只執行一次。
代碼塊面試題:
class Student
{
static
{
System.out.println("Student 靜態代碼塊");
}
{
System.out.println("Student 構造代碼塊");
}
public Student()
{
System.out.println("Student 構造方法");
}
}
class Demo2_Student
{
static
{
System.out.println("Demo2_Student靜態代碼塊");
}
public static void main(String[] args)
{
System.out.println("我是main方法");
Student s1 = new Student();
Student s2 = new Student();
}
}
結果:
Demo2_Student靜態代碼塊
我是main方法
Student靜態代碼塊
Student構造代碼塊
Student構造方法
Student構造代碼塊
Student構造方法