I have enum
enum Number{
FIRST(123),
SECOND(321);
}
Number nr=Number.FIRST
How can I get an enum value (not a String but int ) from my variable nr without creating a new method?
In Java, enums are objects too. Provide a constructor for your numbers to be passed in, plus a public instance variable; no getter method necessary.
enum Num{
FIRST(123),
SECOND(321);
public final int value;
private Num(int value) { this.value = value; }
}
private modifier for the enum constructor is redundant, it is private by definitionYou need to write your enum like this (also, do not call it Number please! There is java.lang.Number):
enum MyNumber
{
FIRST(123),
SECOND(321);
private final int number;
MyNumber(final int number)
{
this.number = number;
}
public int getNumber()
{
return number;
}
}
If you don't want an accessor, remove the getter and make number public.
TL;DR: You can't.
Long version:
The code snippet you have above will not compile because you are missing the constructor:
private int value;
public Number(int i) {
this.value = i;
}
After you've done that, then you will need to provide the getter for value:
public int getValue() {
return this.value;
}
EDIT: If you really, really, don't want to create a new method, you can make the value field public, but you're violating the OO concept of encapsulation (ie, best practice).
some.other.package), then some.other.package.Number will be used instead of java.lang.Number unless you import java.lang.Number specifically.
0) or the number you have next toFIRSTin the declaration (123)?enumwon't compile. You need a constructor that takes anint. And you will need to create a method.