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
class SomeClass{
public SomeClass() { System.out.println("creating SomeClass object"); }
}
class StaticTest{
static{ System.out.println("static block 1"); }
static SomeClass sc = new SomeClass();
static{ System.out.println("static block 2"); }
public static void main(String[] args) {
new StaticTest();
}
}
output
static block 1
creating SomeClass object
static block 2
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: