Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

static init block runs after non-static init block

 
Richard Hayward
Ranch Hand
Posts: 114
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The compiler doesn't complain if I add init blocks to an enum:



However, when I run the program, the enum's static init block executes after it's non-static blocks:

>java TestAnimals
Animals init block 1
Animals init block 2
Animals constructor
Animals init block 1
Animals init block 2
Animals constructor
Animals init block 1
Animals init block 2
Animals constructor
Animals static init block
woof


I was expecting an enum to behave like a class, where static init blocks run before both instance init blocks and the constructor.

Regards
Richard
 
Mala Gupta
Author
Ranch Hand
Posts: 296
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Richard,

When you create an enum, Java adds implicit modifiers to its members. For an example, I created a very simple enum:


and decompiled its .class file using a decompiler (JAD). Here's what I got:



As you can see in the above decompiled code, the enum constants are static members that are initialized within a static initializer. Try and decompile the .class file of your enum 'Animals' and see for yourself the implicit modifiers that are added to its members. This is the reason why your enum doesn't seem to behave the way you assumed :-)

With respect,
Mala

 
Richard Hayward
Ranch Hand
Posts: 114
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for such a detailed answer Mala.
That's interesting!

Regards
Richard
 
Deepak Lal
Ranch Hand
Posts: 561
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@Mala,
Can we expect questions of this type in OCA7 exam.i have not encountered usage of non static init block with init block and enums while preparation for OCA7JP in K&B 6 book(Mala,However are such topics covered in your book for cert preparation)
A nice tricky example.

Regards,
Deepak Lal

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic