简体   繁体   English

创建Java枚举的替代方法?

[英]Alternative way to create a java enum?

I have the following code that I am trying to understand: 我尝试理解以下代码:

public class A {    
    enum Size {S, M, L };  
    Size size = Size.M; 
} 

I understand the first enum line is creating an enum with three values but what is the second line doing? 我知道第一枚举数行正在创建具有三个值的枚举,但是第二枚举数行在做什么? What will the variable size hold and is this another way to construct an enum? 可变大小将保持什么,这是构造枚举的另一种方式吗?

The second line is just giving to the field size (of type Size ) of the instance of class A the initial value Size.M . 第二行只是为A类实例的字段size (类型为Size )赋予初始值Size.M

You may be a little disturbed here by the fact that the enum is created inside the class A , it could have been in another file (but it's perfectly OK to put it inside the class A if it's used only there). 枚举是在类A内创建的,您可能会对此感到不安,它可能已经在另一个文件中(但是,如果仅在其中使用它,则可以将其放入类A中是完全可以的)。


EDIT (not really part of the answer) : here's a (not pretty) exemple of enum declaration so that you can better understand the form of an enum declaration : 编辑(实际上不是答案的一部分):这是枚举声明的一个(不太漂亮的)示例,以便您可以更好地理解枚举声明的形式:

public enum QueryError {

    no_request("no_request", "No request in client call"),
    no_alias_requested("no_alias_requested", "no alias requested"),
    session_not_found("session_not_found", "wrong session id"),
    synosteelQuery_not_found("sxxx_not_found", "sxxx not found");

    public JsonpServerResponse.Error error;

    private QueryError(String type, String details) {
        this.error = new JsonpServerResponse.Error();
        this.error.type = type;
        this.error.detail = details;
    }
}

第二个类似的方法是在类A声明一个类型为Size的包私有成员变量,并将其初始化以指向Size.M

An enum is a type (just as a class is a type). 枚举是类型(就像类是类型一样)。 The second line is creating an instance variable called size, which has a type of Size (since an enum is a type). 第二行正在创建一个名为size的实例变量,该实例变量具有Size的类型(因为枚举是一种类型)。 Then it's initializing the value of that instance variable to an instance of the enum Size (specifically, the Size.M instance). 然后,它将实例变量的值初始化为枚举Size的实例(特别是Size.M实例)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM