標籤:多個 順序 pre 方法 面試 out code stat 不同
代碼塊
/* 代碼塊:在Java中,使用{}括起來的代碼被稱為代碼塊。 根據其位置和聲明的不同,可以分為 局部代碼塊:局部位置,用於限定變數的生命週期。 構造代碼塊:在類中的成員位置,用{}括起來的代碼。每次調用構造方法執行前,都會先執行構造代碼塊。 作用:可以把多個構造方法中的共同代碼放到一起,對對象進行初始化。 靜態代碼塊:在類中的成員位置,用{}括起來的代碼,只不過它用static修飾了。 作用:一般是對類進行初始化。 面試題? 靜態代碼塊,構造代碼塊,構造方法的執行順序? 靜態代碼塊 -- 構造代碼塊 -- 構造方法 靜態代碼塊:只執行一次 構造代碼塊:每次調用構造方法都執行*/class Code { static { int a = 1000; System.out.println(a); } //構造代碼塊 { int x = 100; System.out.println(x); } //構造方法 public Code(){ System.out.println("code"); } //構造方法 public Code(int a){ System.out.println("code"); } //構造代碼塊 { int y = 200; System.out.println(y); } //靜態代碼塊 static { int b = 2000; System.out.println(b); }}class CodeDemo { public static void main(String[] args) { //局部代碼塊 { int x = 10; System.out.println(x); } //找不到符號 //System.out.println(x); { int y = 20; System.out.println(y); } System.out.println("---------------"); Code c = new Code(); System.out.println("---------------"); Code c2 = new Code(); System.out.println("---------------"); Code c3 = new Code(1); }}
看程式,寫結果:
/* 寫程式的執行結果。 分析過程: 載入class時,先執行A, main主方法,執行B, new student()第一次前,載入student class,執行C, new student()第一次時,執行E,再執行D。因為構造方法放在構造代碼塊前,也會先執行構造代碼塊 new student()第二次前,不再執行C,因為靜態代碼塊只執行一次 new student()第二次時,執行E,再執行D。 執行順序: 林青霞都60了,我很傷心 我是main方法 --- Student 靜態代碼塊 Student 構造代碼塊 Student 構造方法 Student 構造代碼塊 Student 構造方法*/class Student { //C static { System.out.println("Student 靜態代碼塊"); } //D public Student() { System.out.println("Student 構造方法"); } //E { System.out.println("Student 構造代碼塊"); } }class StudentDemo { static { //A System.out.println("林青霞都60了,我很傷心"); } public static void main(String[] args) { //B System.out.println("我是main方法"); Student s1 = new Student(); Student s2 = new Student(); }}
08-02 Java 代碼塊,代碼塊執行的先後順序問題