Sam
Sam

Reputation: 467

Why do I have to create an instance of an enum in Java?

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?

Upvotes: 1

Views: 925

Answers (1)

Gelunox
Gelunox

Reputation: 792

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;
}

Upvotes: 2

Related Questions