用以下幾個例子說明
class AAA {
static {
System.out.println("class AAA static block println");
// 並沒有打印此句 }
}
public class Main {
public static void main(String[] args) {
System.out.println("hello world!");
} }
打印結果:
hello world!
----------------------------------------------------------------------------------------------------------------------------------------------------------------
class xx {
final static int x=0;
static {
System.out.println("class AAA static block println");
}
}
public class AAA {
public static void main(String[] args) {
xx xx = new xx();
System.out.println("hello world!");
}
}
打印結果:
class AAA static block println
hello world!
----------------------------------------------------------------------------------------------------------------------------------------------------------------
class xx {
final static int x=0;
static {
System.out.println("class AAA static block println"); // 並沒有打印此句
}
}
public class AAA {
public static void main(String[] args) {
System.out.println("hello world!"+xx.x);
}
}
打印結果:
hello world!0
----------------------------------------------------------------------------------------------------------------------------------------------------------------
class xx {
static int x=0;
static {
System.out.println("class AAA static block println"); // 並沒有打印此句
}
}
public class AAA {
public static void main(String[] args) {
System.out.println("hello world!"+xx.x);
}
打印結果:
class AAA static block println
hello world!0
在《深入理解Java虛擬機:JVM高級特性與最佳實踐 第2版》中找到一些線索,如下圖:
你可以這樣理解,static靜態部分是屬於類本身的。初始化類,其類變量和靜態塊就會加載。
首先java虛擬機允許預加載某個類,一般時候是使用某個類的時候纔會初始化這個類(您的代碼並沒有觸發初始化這個類的條件),畢竟沒有必要初始化不實用的類或者接口占用內存。
JAVA用的按需加載的策略,你代碼裏面完全沒有用到AAA這個類,自然不會去執行