枚举 - 静态和实例块 [英] Enums - static and instance blocks
问题描述
enums
的情况是相反的? 任何人都可以向我解释示例代码的输出:咖啡大小{
BIG(8),LARGE(10),HUGE(12),OVERWHELMING( );
private int盎司;
static {
System.out.println(static block);
}
{
System.out.println(instance block);
}
私人CoffeeSize(int盎司){
this.ounces =盎司;
System.out.println(盎司);
}
私人CoffeeSize(){
this.ounces = 20;
System.out.println(盎司);
}
public int getOunces(){
return盎司;
}
}
输出:
实例块
8
实例块
10
实例块
12
实例块
20
静态块
你必须知道枚举的元素也是静态的,调用静态元素的顺序取决于它的位置。看这个例子
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();
}
}
输出
静态块1
创建SomeClass对象
静态块2
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 must know that elements of enum are also static, and order of invoking static element depends on its 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
这篇关于枚举 - 静态和实例块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!