Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a java enum have more than one constructor?

Tags:

java

I understand I can create an enum like this:

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 some questions:

1) It seems that the enum values are declared at the start. Is there a particular format for this. Could I declare them anywhere?

2) Is is possible to declare an enum with more than one constructor and is this something that people sometimes do?

like image 280
Alan2 Avatar asked Jun 14 '12 16:06

Alan2


2 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;
   }
}
  1. Yes, you must declare the enum values at the start. Always.
  2. See code above. It is possible. If people do it depends on the application. If you have a lot of fields and most of them should be a default value, it is a good thing to use multiple constructors. Also, the values for the fields could be read at runtime (from a file or another static class).
like image 125
brimborium Avatar answered Oct 14 '22 12:10

brimborium


  1. Yes, they must be declared before other fields of the enum class.
  2. Yes, they can have more than one constructor.

You could have discovered by trying it yourself.

like image 33
JB Nizet Avatar answered Oct 14 '22 11:10

JB Nizet