主動使用和被動使用Demojava
一、建立工程一個Gradle工程spa
下一步對象
下一步blog
點擊完成io
二、建立類class
public class MyTest1 { public static void main(String[] args) { System.out.println(MyChild1.str); } } class MyParent1{ public static String str = "hello world"; static { System.out.println("MyParent1 static block"); } } class MyChild1 extends MyParent1{ static { System.out.println("MyChild static block"); } }
輸出結果:配置
MyParent1 static block hello world
會發現MyChild1的類靜態塊沒有執行。im
總結:對於靜態字段來講,只有直接定義了該字段的類纔會被初始化。d3
修改後的類:總結
public class MyTest1 { public static void main(String[] args) { System.out.println(MyChild1.str2); } } class MyParent1{ public static String str = "hello world"; static { System.out.println("MyParent1 static block"); } } class MyChild1 extends MyParent1{ public static String str2 = "hello world 2"; static { System.out.println("MyChild static block"); } }
執行結果
MyParent1 static block MyChild static block hello world 2
由於使用到了MyChild的類,它會被初始化。當一個類在初始化時,要求其父類所有都已經初始化完畢。最終打印結果如上面所示。
三、上面1中,MyChild1沒有被實例化,那MyChild類是否有被加載?
-XX:+TraceClassLoading, 用於追蹤類的加載信息並打印出來
配置以下:
完整的代碼
public class MyTest1 { public static void main(String[] args) { System.out.println(MyChild1.str); } } class MyParent1{ public static String str = "hello world"; static { System.out.println("MyParent1 static block"); } } class MyChild1 extends MyParent1{ public static String str2 = "hello world 2"; static { System.out.println("MyChild static block"); } }
打印的結果
說明MyChild類也會被加載, 最早加載的是MyTest1類
JVM參數
-XX:+<option>, 表示開啓option選項
-XX:+<option> 表示關閉options選項
-XX:<option>=<value>, 表示將option選項的值設置爲value
四、首次主動使用例子
public class MyTest4 { public static void main(String[] args) { MyParent4 myParent4 = new MyParent4(); System.out.println("-------------"); MyParent4 myParent5 = new MyParent4(); } } class MyParent4{ static { System.out.println("MyParent4 static block"); }
打印結果:
MyParent4 static block -------------
說明在建立MyParent4 對象的時候,會初始化MyParent4, 可是第二次建立MyParent4的時候,就不會初始化MyParent4。全部只在主動首次使用纔會初始化。