简体   繁体   中英

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

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 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 ):

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. But it will only be accessible within your class ( EnumThing ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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