Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I declare enums using java

Tags:

java

enums

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"; } 
like image 740
newbie Avatar asked Aug 10 '11 07:08

newbie


People also ask

How do you declare an enum?

An enum is defined using the enum keyword, directly inside a namespace, class, or structure. All the constant names can be declared inside the curly brackets and separated by a comma. The following defines an enum for the weekdays. Above, the WeekDays enum declares members in each line separated by a comma.

How do you create an enum object in Java?

An enum can, just like a class , have attributes and methods. The only difference is that enum constants are public , static and final (unchangeable - cannot be overridden). An enum cannot be used to create objects, and it cannot extend other classes (but it can implement interfaces).

Can we initialize enum in Java?

You can't create an instance of Enum using new operators. It should have a private constructor and is normally initialized as: ErrorCodes error = ErrorCodes. BUSSINESS_ERROR. Each constant in the enum has only one reference, which is created when it is first called or referenced in the code.

What is enum in Java with example?

An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.


2 Answers

public enum MyEnum {    ONE(1),    TWO(2);    private int value;    private MyEnum(int value) {       this.value = value;    }    public int getValue() {       return value;    } } 

In short - you can define any number of parameters for the enum as long as you provide constructor arguments (and set the values to the respective fields)

As Scott noted - the official enum documentation gives you the answer. Always start from the official documentation of language features and constructs.

Update: For strings the only difference is that your constructor argument is String, and you declare enums with TEST("test")

like image 129
Bozho Avatar answered Oct 02 '22 10:10

Bozho


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;     } } 
like image 39
JB Nizet Avatar answered Oct 02 '22 09:10

JB Nizet