user195488
user195488

Reputation:

Return enum value without calling get function

Is it possible in Java to return the enum value without having to call a function to return the value, such as getFlag() in my example? If so, how?

public enum MessageFlags {
        BIT0((short)1),
        BIT1((short)2),
        BIT2((short)4),
        BIT3((short)8),
        BIT4((short)16),
        BIT5((short)32),
        BIT6((short)64),
        BIT7((short)128),
        BIT8((short)256),
        BIT9((short)512),
        BIT10((short)1024),

        set_freq(BIT0),
        get_freq(BIT1);

        short bitFlag = 0;
        MessageFlags flag;

        MessageFlags(short flag) {
            this.bitFlag = flag;
        }

        MessageFlags(MessageFlags flag) {
            this.flag = flag;
        }

        public short getFlag() {
            return this.flag.bitFlag;
        }

        public short getValue() {
            return this.bitFlag;
        }
    }

Upvotes: 2

Views: 1142

Answers (4)

Nesze
Nesze

Reputation: 1

I might be really late, but I'm writing to anyone who visits this topic for help.

If you have an enum, and you'd like to return a specific parameter of its values by default without calling a get function, you need to insert an @Override above your selected function, like:

public class Plants {
  public enum Fruits {
    APPLE ("sweet"),
    GRAPEFRUIT ("sour");

    private String taste;

    Fruits (String taste) {
      this.taste = taste;
    }

    @Override
    public String getTaste() {
      return this.taste;
    }
  }
}

And now you can call whichever enum value you'd like, without a get function:

Plants.Fruits.APPLE

And it'll return "sweet"

P.S. I'm not a professional programmer, please correct me if I've written something anti-conventional by accident.

Upvotes: 0

user195488
user195488

Reputation:

I followed @Jeremy's advice of this:

package foo;

import static foo.B.*;

and then I created a method called set_freq in my MessageFlags enum. I made this function static and had it return short. For example,

public static short set_freqflag() {
    return BIT0.getFlag();
}

The semantics of set_freqflag are a little weird because you are not setting anything but I do not have a better name at the moment. This allows me to just state set_freqflag() rather than the longer way I was doing before.

Upvotes: 1

Jeremy
Jeremy

Reputation: 22415

You can import static MessageFlags.*; and say BITX.getFlag().

Here is a complete example:

A.java

package foo;

import static foo.B.*;

public class A{
    public B value = BAR;
}

B.java

package foo;

public enum B{
    BAR, BAZ, BOO
}

Upvotes: 2

Hunter McMillen
Hunter McMillen

Reputation: 61512

Just say MessageFlags.BITX and that will return the same value as getFlag()

Upvotes: 3

Related Questions