Cristian Cristian - 11 months ago 37
Java Question

Java Enum return Int

I'm having trouble declaring an enum. I've read up on the documentation but can't figure it out.

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 {
private final int value;

private DownloadType(int value) {
this.value = value;

This works fine if I then use it like this:


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:


Which returns an int value, we don't use:


I must have misunderstood something because I can't figure this out.

Thanks in advance everyone


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 as int also:

static class DownloadType {
    public static final int AUDIO = 0;
    public static final int VIDEO = 1;
    public static final int AUDIO_AND_VIDEO = 2;

By the way, the value field is actually redundant because there is also an .ordinal() method, so you could define the enum as:

enum DownloadType { AUDIO, VIDEO, AUDIO_AND_VIDEO }

and get the "value" using