4

阅读此问题后,当类加载到 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
4

2 回答 2

7

为什么在初始化超类的静态变量和静态块之后,控制权交给子类进行静态变量初始化,而不是完成实例成员的初始化?

因为静态初始化发生一次,在创建任何实例之前。

静态对应于类,非静态对应于特定实例。

于 2013-03-06T17:49:00.087 回答
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
于 2013-03-06T17:53:59.403 回答