I’m having trouble declaring an enum. What I’m trying to create is an enum for a ‘DownloadType’, where there are 3 download types (AUDIO, VIDEO, AUDIO_AND_VIDEO).
I have implemented the code as follows:
private enum DownloadType {
AUDIO(0), VIDEO(1), AUDIO_AND_VIDEO(2);
private final int value;
private DownloadType(int value) {
this.value = value;
}
}
This works fine if I then use it like this:
DownloadType.AUDIO_AND_VIDEO.value;
However, I would like it so that I don’t have to ask for the ‘value’. I may be mistaken, but this is the way several classes work in Java such as Font, for example to set a font style, you use:
Font.PLAIN
Which returns an int value, we don’t use:
Font.PLAIN.value
Font.PLAIN is not an enum. It is just an
int. If you need to take the value out of an enum, you can’t avoid calling a method or using a.value, because enums are actually objects of its own type, not primitives.If you truly only need an
int, and you are already to accept that type-safety is lost the user may pass invalid values to your API, you may define those constants asintalso:By the way, the
valuefield is actually redundant because there is also an.ordinal()method, so you could define theenumas:and get the “value” using
Edit: Corrected the code..
static classis not allowed in Java. See this SO answer with explanation and details on how to define static classes in Java.