0

I am not sure whether I have a correct model of Java initialization mechanism in my head. Each class follows the following:

  1. Initialize superclass, if there exists one
  2. Initialize yourself

Initialize follows the following:

  1. Initialize static and instance variables which have their values set outside of initializer.
  2. Run static initialization block
  3. Run constructor block

Is that precise/correct?

Bober02
  • 15,034
  • 31
  • 92
  • 178
  • 1
    There is a difference in initializing an object and loading a class. Static members are initialized when the class is loaded, while non-static members are initialized when an object is created. – scravy Apr 18 '12 at 16:08
  • be careful about what you call "initialization" – UmNyobe Apr 18 '12 at 16:08
  • Possibly a duplicate of http://stackoverflow.com/questions/3499214/java-static-class-initialization – Francisco Paulo Apr 18 '12 at 16:09

2 Answers2

1

According to the Java language specification, your assumptions are more or less correct. The exceptions are that:

  1. instance variables are run when the class is constructed (together with the constructor) after the class is initialized,
  2. final static variables with compile-time constant expressions are loaded before even attempting to load the superclass, and
  3. the static initialization block is run together with the static variables as one block, in the order they appear in the code.
henko
  • 763
  • 7
  • 16
  • I just wanted to write down that I would expect paragraph 1 – stefan bachert Apr 18 '12 at 16:16
  • I would expect that too, I just noted that the question stated the assumption that static and instance variables are initialized together before class construction. – henko Apr 18 '12 at 16:18
1

Code execute as below -

Static init blocks run once, when the class is first loaded.

Static Variable

All Super Constructor.

Instance init blocks run after the constructor's call to super().

instance variable.

(Init blocks execute in the order they appear.)

user207421
  • 305,947
  • 44
  • 307
  • 483
kundan bora
  • 3,821
  • 2
  • 20
  • 29
  • 1
    There is no guarantee that the static init block will run before the static variables. In fact, many static variables (those which are final and have a compile time constant expression) are assigned before the static init block. – henko Apr 18 '12 at 19:08