1

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!

0

2 Answers 2

4

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);
Sign up to request clarification or add additional context in comments.

Comments

2

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

4 Comments

I think it's usually more useful to describe what the problem with OP's code is and provide a solution to it along with an explanation, rather than just providing a "full working example".
Thanks - I'm using an IDE with a workspace which occludes the main method (it seems they think it's a little advanced for us, though it's really not). Are you saying this works as written or were you just formatting it better?
@JonnieMarbles it will work as written . But if you wish to use the SomeConstant enum in a different class then you will have to declare it as protected (if in same package) or public. Then you can access it as: EnumThing.SomeConstant.CONSTANT1 etc...
@Idos thanks for this - I needed to use the full name even when it was declared to "public" due, presumably, to the vagaries of the IDE I'm using. Seriously can't wait to move onto NetBeans rather than this nonsense.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.