阅读此问题后,当类加载到 JVM 中时,类的不同部分以什么顺序初始化?和相关的JLS。我想更详细地了解为什么例如具有以下动物类(超类)和狗类(子类):
class Animal
{
static{
System.out.println("This is Animal's static block speaking"):
}
{
System.out.println("This is Animal's instance block speaking");
}
class Dog{
static{
System.out.println("This is Dog's static block speaking");
}
{
System.out.println("This is Dog's instance block speaking");
}
public static void main (String [] args)
{
Dog dog = new Dog();
}
}
好的,在实例化一个类之前,它的直接超类需要被初始化(因此所有的静态变量和块都需要被执行)。所以基本上问题是:为什么在初始化超类的静态变量和静态块之后,控制权交给子类进行静态变量初始化,而不是完成实例成员的初始化?
控制如下:
superclass (Animal): static variables and static blocks
subclass (Dog): static variables and static blocks
superclass (Animal): instance variables and instance blocks
sublcass (Dog):instance variables and instance blocks
是什么原因导致它以这种方式而不是:
superclass -> static members
superclass -> instance members
subclass -> static members
sublcass-> instance members