简体   繁体   English

在Java中使用枚举创建构造函数

[英]Creating constructors using Enums in Java

I want to define a class with a constructor that takes an enum as a formal argument (so only arguments which conform with the enum type can be passed). 我想用一个将枚举作为正式参数的构造函数定义一个类(因此,只能传递符合枚举类型的参数)。 Here's what I have (generalised as I'm doing college work and don't want to plagiarise): 这是我所拥有的(一般来说,因为我正在上大学并且不想窃):

public class EnumThing
{
private SomeConstant aConstant;
private enum SomeConstant {CONSTANT1, CONSTANT2, CONSTANT3};

public EnumThing(SomeConstant thisConstant)
{
   this.aConstant = thisConstant;
}

// Methods

However when I try 但是当我尝试

EnumThing doodah = new EnumThing(CONSTANT1);

I get an error: cannot find symbol - variable CONSTANT1 我收到一个错误:找不到符号-变量CONSTANT1

This is my first attempt to use enums for anything at all. 这是我第一次尝试将枚举用于所有内容。 They seem excitingly powerful but it seems like I'm using them wrong. 它们似乎功能强大,但似乎我用错了它们。 Any help hugely appreciated! 任何帮助深表感谢!

First of all, you need to make the enum public otherwise you cannot access it outside of the class EnumThing : 首先,您需要public枚举,否则您将无法在EnumThing类之外访问它:

public class EnumThing {
    public enum SomeConstant {CONSTANT1, CONSTANT2, CONSTANT3}

    // ...
}

Then, access the members of the enum correctly: 然后,正确访问枚举的成员:

EnumThing doodah = new EnumThing(EnumThing.SomeConstant.CONSTANT1);

Full working example (note that the correct usage is: SomeConstant.CONSTANT1 ): 完整的工作示例(请注意,正确的用法是: SomeConstant.CONSTANT1 ):

public class EnumThing {
    private SomeConstant aConstant;

    private enum SomeConstant {CONSTANT1, CONSTANT2, CONSTANT3}

    public EnumThing(SomeConstant thisConstant) {
        this.aConstant = thisConstant;
    }

    public static void main(String[] args) {
        EnumThing doodah = new EnumThing(SomeConstant.CONSTANT1);
    }
}

Note that you can use a private enum. 请注意,您可以使用private枚举。 But it will only be accessible within your class ( EnumThing ). 但是它只能在您的班级( EnumThing )中访问。

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

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