unknown_boundaries
unknown_boundaries

Reputation: 1580

Java: class equivalent for an enum

If there is an enum,

public enum Animal {
   DOG,
   CAT;
}

If I'm understanding enums correctly, we can convert them in equivalent class, something like -

public class Animal {
   private static final DOG = 1;
   private static final CAT = 2;
}

Is this the correct representation, or I'm missing anything here?

Thanks.

Upvotes: 0

Views: 2021

Answers (2)

AlexR
AlexR

Reputation: 115328

Not exactly. Here is how it will look like:

public class Animal extends Enum<Enum<Animal>> {
   public static final Animal DOG = new Animal("DOG", 0);
   public static final Animal CAT = new Animal("CAT", 1);
   private static final Animal[] values = new Animal[] {DOG, CAT};

   private Animal(String name, int ordinal) {super(name, ordinal);}
   public static Animal valueOf(String name) {return Enum.valueOf(Animal.class, name)}
   public Animal[] values() {return values;}
}

Class java.lang.Enum holds ordinal and name and provides methods that can access them.

Upvotes: 6

Pshemo
Pshemo

Reputation: 124215

No, your code shows how things ware organized before enum was added in Java 1.5.

  • Your enum values needs to be public not private because you want to make them accessible everywhere.
  • Also they value is instance of your enum class, not integer (you may want to invoke some methods on these instances like TimeUnit.SECONDS.toMinutes(120); where you invoke toMinutes on instance SECONDS)

So your code looks more like

public class Animal extends Enum<Animal>{
    public static final Animal DOG = new Animal();
    public static final Animal CAT = new Animal();

    //rest of code added by compiler, like 
    // - making constructor private
    // - handling `ordinal()` 
    // - adding `valueOf(String) ` and `values()` methods
}

Upvotes: 3

Related Questions