枚举 - 静态和实例块 [英] Enums - static and instance blocks

查看:120
本文介绍了枚举 - 静态和实例块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经了解到,在Java中,当类被初始化并且实例块在构造该类的每个实例之前被执行时,静态块被执行。我一直看到在实例块之前执行的静态块。为什么 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆