[java] How can I declare enums using java

I want to convert this sample C# code into a java code:

public enum myEnum {
  ONE = "one",
  TWO = "two",
}; 

Because I want to change this constant class into enum

public final class TestConstants {
    public static String ONE = "one";
    public static String TWO= "two";
}

This question is related to java enums

The answer is


Quite simply as follows:

/**
 * @author The Elite Gentleman
 *
 */
public enum MyEnum {
    ONE("one"), TWO("two")
    ;
    private final String value;

    private MyEnum(final String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }

    @Override
    public String toString() {
        // TODO Auto-generated method stub
        return getValue();
    }
}

For more info, visit Enum Types from Oracle Java Tutorials. Also, bear in mind that enums have private constructor.


Update, since you've updated your post, I've changed my value from an int to a String.
Related: Java String enum.


public enum MyEnum
{
    ONE(1),
    TWO(2);

    private int value;

    private MyEnum(int val){
        value = val;
    }

    public int getValue(){
        return value;
    }
}

Well, in java, you can also create a parameterized enum. Say you want to create a className enum, in which you need to store classCode as well as className, you can do that like this:

public enum ClassEnum {

    ONE(1, "One"), 
    TWO(2, "Two"),
    THREE(3, "Three"),
    FOUR(4, "Four"),
    FIVE(5, "Five")
    ;

    private int code;
    private String name;

    private ClassEnum(int code, String name) {
        this.code = code;
        this.name = name;
    }

    public int getCode() {
        return code;
    }

    public String getName() {
        return name;
    }
}

public enum NewEnum {
   ONE("test"),
   TWO("test");

   private String s;

   private NewEnum(String s) {
      this.s = s);
   }

    public String getS() {
        return this.s;
    }
}

enums are classes in Java. They have an implicit ordinal value, starting at 0. If you want to store an additional field, then you do it like for any other class:

public enum MyEnum {

    ONE(1),
    TWO(2);

    private final int value;

    private MyEnum(int value) {
        this.value = value;
    }

    public int getValue() {
        return this.value;
    }
}