I had learned that in Java the static block gets executed when the class is initialized and instance block get executed before the construction of each instance of the class . I had always seen the static block to execute before the instance block . Why the case is opposite for enums
?
Can anyone please explain me the output of the sample code :
enum CoffeeSize {
BIG(8), LARGE(10),HUGE(12),OVERWHELMING();
private int ounces ;
static {
System.out.println("static block ");
}
{
System.out.println("instance block");
}
private CoffeeSize(int ounces){
this.ounces = ounces;
System.out.println(ounces);
}
private CoffeeSize(){
this.ounces = 20;
System.out.println(ounces);
}
public int getOunces() {
return ounces;
}
}
Output:
instance block
8
instance block
10
instance block
12
instance block
20
static block
You need to know that enum values are static fields which hold instances of that enum type, and initialization order of static fields depends on their position. See this example
output
Now since enum values are always placed at start of enum type, they will always be called before any static initialization block, because everything else can only be declared after enum values.
BUT initialization of enum values (which happens at class initialization) their constructors are called and as you said non-static initialization blocks are executed at start of every constructor which is why you see them:
Use bytecode to make out this problem.
use javac compile to class file, and then
javap -c EnumDemo.class
, got this:So, enum instance is the static instance, and at the head.
1. An enum type is a type whose fields consist of a fixed set of constants. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.
2. They are static final constant, therefore have all letters in Caps.
3. And static variables are initialized as soon as the JVM loads the class.
For further details see this link:
http://docs.oracle.com/javase/1.5.0/docs/guide/language/enums.html
Little late and building up on Pshemo's answer. The output of the (compiling) code below is as follows:
So the enum constant initializations are executed first (as Pshemo said, they are always implicitly
static
andfinal
, see second blockquote) and then all fields explicitly declared asstatic
are initialized. As mentioned, the language specification says this about the order of execution during class initialization and about enum constants: