wood burning stoves*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes static init block runs after non-static init block Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "static init block runs after non-static init block" Watch "static init block runs after non-static init block" New topic
Author

static init block runs after non-static init block

Richard Hayward
Ranch Hand

Joined: Feb 15, 2012
Posts: 67
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

Joined: Sep 27, 2002
Posts: 248
    
    9
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


Author of Manning's OCA Java SE 7 Programmer I Certification Guide and OCP Java SE 7 Programmer II Certification Guide
Richard Hayward
Ranch Hand

Joined: Feb 15, 2012
Posts: 67
Thank you for such a detailed answer Mala.
That's interesting!

Regards
Richard
Deepak Lal
Ranch Hand

Joined: Jul 01, 2008
Posts: 507

@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


When The Going Gets Tougher,The Tougher gets Going
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: static init block runs after non-static init block
 
Similar Threads
Interface question....
please explain the code and please anyone give example of overloading in enum
can u please explain the ouput of the given code
Problem related to enums
Enums