枚举 - 静态块和实例块
2022-09-01 02:07:57
我了解到,在Java中,静态块在类初始化时执行,实例块在构造类的每个实例之前执行。我总是看到在实例块之前执行的静态块。为什么情况相反?enums
任何人都可以解释一下示例代码的输出:
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;
}
}
输出:
实例块
8
实例块
10
实例块
12
实例块
20
静态块