一個類被加載,當且僅當其某個靜態成員(靜態域、構造器、靜態方法等)被調用時發生。 學習
那麼加載一個類時,靜態內部類是否是被看作「靜態代碼塊」同時被加載了?下面咱們作一個實驗來看一下。 spa
- public class Outer {
- static {
- System.out.println("load outer class...");
- }
-
-
- static class StaticInner {
- static {
- System.out.println("load static inner class...");
- }
-
- static void staticInnerMethod() {
- System.out.println("static inner method...");
- }
- }
-
- public static void main(String[] args) {
- Outer outer = new Outer();
- System.out.println("===========分割線===========");
- Outer.StaticInner.staticInnerMethod();
- }
- }
運行結果:
load outer class...
==========分割線==========
load static inner class...
static inner method...
調用構造方法時,外部類Outer被加載,但這時其靜態內部類StaticInner卻未被加載。直到調用該內部類的靜態方法(在分割線如下),StaticInner才被加載。
延伸學習:對象
根據內部類不會在其外部類被加載的同時被加載的事實,咱們能夠引伸出單例模式的一種實現方式: 靜態內部類資源
- public class Singleton {
- private Singleton() {}
-
- static class SingletonHolder {
- private static final Singleton instance = new Singleton();
- }
-
- public static Singleton getInstance() {
- return SingletonHolder.instance;
- }
- }
該「靜態內部類」實現單例模式的方式,在單例對象佔用資源大,須要延時加載的狀況下優選。get