JAVA - 深入JAVA 虚拟机 3

时间:2022-01-22 14:56:10

类的初始化时机

JAVA - 深入JAVA 虚拟机 3

package practise;

class Parent{

    static int a =3;
static{ System.out.println("Parent static block");
}
}
class Child extends Parent
{
static int b = 4;
static{ System.out.println("Child static block");
}
}
public class Test4 { static{ System.out.println("Test4 static block");
}
public static void main(String[] args) { System.out.println(Child.b); }
} Result:
Test4 static block
Parent static block
Child static block
4
package practise;

class Parent5{

    static int a =3;
static{ System.out.println("Parent5 static block");
}
}
class Child5 extends Parent5
{
static int b = 4;
static{ System.out.println("Child5 static block");
}
}
public class Test5 { static{ System.out.println("Test5 static block");
}
public static void main(String[] args) { Parent5 parent = new Parent5(); System.out.println(Parent5.a);
System.out.println(Child5.b); }
} Result:
Test5 static block
Parent5 static block
3
Child5 static block
4 程序中对子类的“主动使用”会导致父类被初始化;但对父类的“主动”使用并不会导致子类
初始化。

调用 ClassLoader类的loadClass方法加载一个类,并不是对类的主动使用,不会导致类的初始化。

package practise;

class C{

    static{

        System.out.println("Class C");
}
} public class Test6 {
public static void main(String[] args) { ClassLoader loader = ClassLoader.getSystemClassLoader(); try {
Class<?> clz = loader.loadClass("practise.C");
System.out.println("----------------");
clz = Class.forName("practise.C"); } catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} Result:
----------------
Class C