虛擬機不會初始化類的三種情況

子類使用父類的靜態字段時,只有直接定義這個字段的父類會被初始化。

public class JVMTest {
    public static void main(String[] args) {
        System.out.println(Son.a);
    }
}

class Father{
    public static int a=1;

    static {
        System.out.println("父類初始化");
    }
}

class Son extends Father{

    static {
        System.out.println("子類初始化");
    }
}

結果:子類未被初始化

在這裏插入圖片描述


通過數組定義來使用類。

定義單獨一個對象

public class JVMTest {
    public static void main(String[] args) {
        Father father=new Father();
    }
}

class Father{
    public static int a=1;

    static {
        System.out.println("父類初始化");
    }
}

父類被初始化了
在這裏插入圖片描述
通過數組定義

public class JVMTest {
    public static void main(String[] args) {
        Father[] fathers=new Father[10];
    }
}

class Father{
    public static int a=1;

    static {
        System.out.println("父類初始化");
    }
}

不會初始化
在這裏插入圖片描述


常量在編譯期會存入調用類的常量池,因此不會初始化定義常量的類。

public class JVMTest {
    public static void main(String[] args) {
        System.out.println(Father.b);
    }
}

class Father{
    public static int a=1;
    public static final int b=1;
    static {
        System.out.println("父類初始化");
    }
}

定義常量b的Father類沒有被初始化
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章