根據(jù)上一節(jié)的理論我們知道,每個(gè)類的接口被Java程序“首次主動(dòng)使用”時(shí)才初始化,這一節(jié)我們就通過具體的實(shí)例來驗(yàn)證一下
- 創(chuàng)建類的實(shí)例
public class MyTest1 {
public static void main(String[] args) {
new MyParent1();
}
}
class MyParent1 {
public static String str = "hello world";
static {
System.out.println("MyParent static block");
}
}
運(yùn)行程序,輸出:
MyParent static block
類的靜態(tài)代碼塊被執(zhí)行了,說明類進(jìn)行了初始化
- 訪問某個(gè)類或接口的靜態(tài)變量,或者對(duì)該靜態(tài)變量賦值
public class MyTest1 {
public static void main(String[] args) {
System.out.println(MyParent1.str);
}
}
class MyParent1 {
public static String str = "hello world";
static {
System.out.println("MyParent static block");
}
}
運(yùn)行程序,輸出:
MyParent static block
hello world
- 調(diào)用類的靜態(tài)方法
public class MyTest1 {
public static void main(String[] args) {
MyParent1.print();
}
}
class MyParent1 {
public static String str = "hello world";
public static void print(){
System.out.println(str);
}
static {
System.out.println("MyParent static block");
}
}
運(yùn)行程序,輸出:
MyParent static block
hello world
- 反射
public class MyTest1 {
public static void main(String[] args) throws ClassNotFoundException {
Class.forName("com.shengsiyuan.jvm.classloader.MyParent1");
}
}
class MyParent1 {
public static String str = "hello world";
static {
System.out.println("MyParent static block");
}
}
運(yùn)行程序,輸出:
MyParent static block
- 初始化一個(gè)類的子類
public class MyTest1 {
public static void main(String[] args) throws ClassNotFoundException {
new MyChild1();
}
}
class MyParent1 {
public static String str = "hello world";
static {
System.out.println("MyParent static block");
}
}
class MyChild1 extends MyParent1 {
public static String str2 = "welcome";
static {
System.out.println("MyChild1 static block");
}
}
運(yùn)行程序,輸出:
MyParent static block
MyChild1 static block
- Java虛擬機(jī)啟動(dòng)時(shí)被表明為啟動(dòng)類的類
public class MyTest1 {
static {
System.out.println("MyTest1 static block");
}
public static void main(String[] args) throws ClassNotFoundException {
}
}
運(yùn)行程序,輸出:
MyTest1 static block
非主動(dòng)使用注意點(diǎn)
以上實(shí)例都是對(duì)主動(dòng)使用的驗(yàn)證,我們來看一下下面這個(gè)程序
public class MyTest1 {
public static void main(String[] args) throws ClassNotFoundException {
System.out.println(MyChild1.str);
}
}
class MyParent1 {
public static String str = "hello world";
static {
System.out.println("MyParent static block");
}
}
class MyChild1 extends MyParent1 {
static {
System.out.println("MyChild1 static block");
}
}
運(yùn)行程序,輸出:
MyParent static block
hello world
我們可以看到,MyChild1 static block并沒有打印出來,這里我們調(diào)用MyChild1.str明明是對(duì)類的靜態(tài)變量的訪問,但是MyChild1卻沒有被初始化,所以這里要注意的一點(diǎn)就是:
對(duì)于靜態(tài)字段來說,只有直接定義了該字段的類才會(huì)被初始化
參考資料:
圣思園JVM課程