static block instance block java Order

Posted by Rollerball on Stack Overflow See other posts from Stack Overflow or by Rollerball
Published on 2013-03-06T17:46:56Z Indexed on 2014/06/04 21:25 UTC
Read the original article Hit count: 294

Filed under:
|
|

Having read this question In what order are the different parts of a class initialized when a class is loaded in the JVM? and the related JLS. I would like to know in more detail why for example having class Animal (superclass) and class Dog (subclass) as following:

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();
}
}

Ok before instantiating a class its direct superclass needs to be initialized (therefore all the statics variables and block need to be executed). So basically the question is: Why after initializing the static variables and static blocks of the super class, control goes down to the subclass for static variables initialization rather then finishing off the initialization of also the instance member?

The control goes like:

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

What is the reason why it is in this way rather than :

superclass -> static members
superclass -> instance members
subclass -> static members
sublcass-> instance members

© Stack Overflow or respective owner

Related posts about java

Related posts about block