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"; }
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.
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).
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.
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.
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")
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; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With