Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static block instance block java Order

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
like image 910
Rollerball Avatar asked Jan 15 '23 00:01

Rollerball


2 Answers

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?

Because static initialization happens once, before any instances are created.

Statics correspond to the class, non-statics correspond to a particular instance.

like image 50
Oliver Charlesworth Avatar answered Jan 19 '23 12:01

Oliver Charlesworth


It makes sense if you create more dogs

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
like image 31
irreputable Avatar answered Jan 19 '23 12:01

irreputable