• Post Reply Bookmark Topic Watch Topic
  • New Topic

Initializatio order  RSS feed

 
Matt Road
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Hello ,

could you help me please find out why the ouput of this code is "2 4 6 8 5" ?

After The two static (add(2) and add(4) ) it should run the "new Hello" initialization, so it should restart to run all the static order from the beginning. I think that it should start an infinite loop. WHere I wrong ?

Thank you
 
Knute Snortum
Sheriff
Posts: 4091
112
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The way I'd put it, all the static initializers are executed in order, then the instance initializers in order, then the constructor.
 
Matt Road
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
but when you initialize the first thing that should run won't be the constructor ?
 
Knute Snortum
Sheriff
Posts: 4091
112
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Surprisingly no. Everything that belongs to the class (that is, static) gets executed first. This allows you to set up static members that may be needed in the constructor first. Then instance initializers for the same reason. Since includes may have initializers, they are executed from the top down.
 
Mike. J. Thompson
Bartender
Posts: 689
17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The reason you don't get an infinite loop of initalisations is that the static initialisers are only run once as part of class loading. They do not run every time an instance is created.

As already pointed out the constructor will be the last thing to run in your code. The static initialisers come first (in textual order), followed by the non-static initialisers (also in textual order) .
 
Sachin Tripathi
Ranch Hand
Posts: 368
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why not try to see like this:
static initializer are executed at class loading time

instance initializer are the next


Then constructors works
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!