1
public enum itemType{
  COMPANYY_WIDE("Company"),
  DEPARTMENTAL("Departmental"),
  PROJECT_SPECIFIC("Project");

  private String itemCode;

  private itemType(String dbCode){
      this.itemCode=dbCode;
  }

  public static void main(String[] args) {
      itemType type3=new itemType("Project");// line 1 
      itemType type2=itemType.valueOf("PROJECT_SPECFIFIC");// line 2
      itemType type4=itemType.values()[0];// line 3
      itemType type1=itemType.DEPARTMENTAL;
   }
}

So enum itemType has 4 types and each type has an attribute itemcode which is also the dbcode. I try initializing the enum types with different approaches in main but I have some confusion. Why line 1 does not work? Why line 2 and line 3 will work?

rev_dihazum
  • 818
  • 1
  • 9
  • 19
user6119494
  • 65
  • 1
  • 7
  • take a look at this: http://stackoverflow.com/questions/19971982/enum-class-initialization-in-java – Erick Apr 12 '16 at 01:47

1 Answers1

0

In Java, enum is a special type class which has fixed number of object.

For your case, itemType has exactly three object named COMPANYY_WIDE, DEPARTMENTAL, PROJECT_SPECIFIC. You cant create any new object at runtime for enum.

You could read this Java-Doc Java Enum

rev_dihazum
  • 818
  • 1
  • 9
  • 19
  • Nice explanation! since we cannot create new object, what is the meaning of having a constructor inside the enum? @rev_dihazum – user6119494 Apr 12 '16 at 01:51
  • @user6119494 the constructor is used only once to load the item initially. – flakes Apr 12 '16 at 01:54
  • Constructor used to set properties of ``enum``. for example if you have another property of your enum type i.e. ``private int itemId;`` then you need to modify your constructor as ``itemType(String dbCode, int id){ this.itemCode=dbCode; this.itemId = id; }`` and declare objects as ``COMPANYY_WIDE("Company", 1)`` – rev_dihazum Apr 12 '16 at 01:57
  • "load the item initally" you mean match the type to their item code? @flkes – user6119494 Apr 12 '16 at 01:57
  • @user6119494 , hey! as you accepted it as answer it would be nice to upvote it to appreciate. – rev_dihazum May 31 '16 at 07:08