阅读了这个问题In what order are the different parts of a class initialized when a class is loaded in the JVM?和相关的JLS。我想更详细地了解为什么例如具有类Animal(超类)和类Dog(子类)如下:
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
答案 0 :(得分:7)
为什么在初始化超类的静态变量和静态块之后,控制会转到静态变量初始化的子类,而不是完成实例成员的初始化?
因为静态初始化发生一次,所以在创建任何实例之前。
静态对应于类,非静态对应于特定实例。
答案 1 :(得分:2)
如果你创造更多狗
是有道理的superclass (Animal): static variables and static blocks
subclass (Dog) : static variables and static blocks
superclass (Animal): instance variables and instance blocks
subclass (Dog) : instance variables and instance blocks
superclass (Animal): instance variables and instance blocks
subclass (Dog) : instance variables and instance blocks
superclass (Animal): instance variables and instance blocks
subclass (Dog) : instance variables and instance blocks