子類使用父類的靜態字段時,只有直接定義這個字段的父類會被初始化。
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類沒有被初始化