Can java enum have more than one constructor?

I understand that I can create an enumeration as follows:

public enum MyEnum {
   ONE(1),
   TWO(2);
   private int value;
   private MyEnum(int value) {
      this.value = value);
   }
   public int getValue() {
      return value;
   }
}

But I have a few questions:

1) It seems that the enumeration values ​​are declared at the beginning. Is there a specific format for this. Can I declare them anywhere?

2) Is it possible to declare an enumeration with more than one constructor, and this is what people sometimes do?

+5
source share
3 answers
public enum MyEnum {
   ONE(1),
   TWO(1, 2);
   private int value1, value2;

   private MyEnum(int value) {
      this.value1 = value;
      this.value2 = 0; // default
      // this.value2 = getFromSomewhereElse(); // get it at runtime
   }

   private MyEnum(int value1, int value2) {
      this.value1 = value1;
      this.value2 = value2;
   }

   public int getValue1() {
      return this.value1;
   }

   public int getValue2() {
      return this.value2;
   }
}
  • Yes, you must declare the enumeration values ​​at the beginning. Is always.
  • . . . , . , , . , ( ).
+5
  • , enum.
  • , .

, .

+8
  • JLS 7, .

  • "Any constructor or member declarations in an enumeration declaration apply to the enumeration type exactly as if they were present in the class cube of a normal class declaration, unless otherwise specified." and "This is a compile-time error if the declaration of an enumeration type constructor is public or secure." (ibid., 8.9.2)

+3
source

All Articles