1

I'm new to Java and I can't seem to find the answer for this question even though it seems so simple.

I come from a C background and use to creating enums and using them by just calling the name of the enum like so...

enum Security_Levels 
        { 
          black_ops, 
          top_secret, 
          secret, 
          non_secret 
        }; 

So I could use black_ops and I would get a 0.

In Java you can define an enum in a separate folder and import it to where you want to use it. But unlike C I can't make a simple call to the enum objects.

public enum GroupID
{
    camera,
    projector,
    preview,
    slr,
    led
}

When I try to call preview it doesn't work... I have to create an instance of the enum object

GroupID egroupid_preview = GroupID.preview;

Then even if I made an instance, I have to create Public functions to access the value as so below.

public enum GroupID
{
    camera(1),
    projector(2),
    preview(3),
    slr(4),
    led(5);

    private int val;

    private GroupID(int val) {
        this.val = val;
    }
    int getVal() {
        return val;
    }
}

Am I doing this all wrong or is there a reason java makes it so hard to access an enum?

Sam
  • 457
  • 2
  • 6
  • 21
  • 3
    "I have to create an instance of the enum object" -- that is not creating an instance. "I have to create Public functions to access the value" -- that is because `enum` does not have to have any sort of "value", and that value would not have to be an `int`. – CommonsWare Jun 01 '16 at 18:06
  • 1
    http://stackoverflow.com/questions/8157755/how-to-convert-enum-value-to-int http://stackoverflow.com/questions/3990319/storing-integer-values-as-constants-in-enum-manner-in-java – Elwin Arens Jun 01 '16 at 18:07
  • 2
    You're thinking of an enum as an int, and that's not actually what it is in Java. Enums _are_ objects. – Louis Wasserman Jun 01 '16 at 18:09
  • Then you can't use enum's in Java like you do in C? What's the point of an enum in Java if you have to define each item? – Sam Jun 01 '16 at 18:21
  • 3
    Yes, you can't use Java like you use C. – zapl Jun 01 '16 at 18:21

1 Answers1

2

Java enumerators are special static objects and do not hold any value by default. They are typically used by name:

enum Foo
{
    foo,
    bar,
    oof;
}

public void func(Foo arg)
{
    if(arg == Foo.bar)
        // do bar code

    switch(arg)
    {
        case foo: // do foo code
        case oof: // do oof code
    }
}

if you need actual values in your enumeration you can use the one with the function you made yourself or do something like this:

enum Foo
{
    foo (1),
    bar (2),
    oof (3);

    public final int val;

    Foo(int val)
    {
        this.val = val;
    }
}

public static void main( String[] args )
{
    Foo f = Foo.bar;

    int val = f.val;
}
Gelunox
  • 772
  • 1
  • 5
  • 23