简体   繁体   中英

How to make objects of an enum in java

I am trying to define three different objects of enum class "Item" with weights between 0 and 20 and description of each item

Here is my code :

public enum Item
{
    // Three Items with descriptions
    GOLD (2, "gold"), SILVER(12, "silver"), BRONZE(5, "bronze");

    private int weight;
    private String description;

    public int getWeight()
    {
       return weight;
    }

    public String toString()
    {
        return description;
    }

}

I keep getting this error

constructor Item in enum Item cannot be applied to given types: required: no arguments, found:int.java.lang.String, reason: actual and formal argument lists differ in length

Also

The operator that you use here cannot be used for the type of value that you are using it for. You either using the wrong type here, or the wrong operator

You forgot to declare a constructor !

public enum Item {

  GOLD(2, "gold"), SILVER(12, "silver"), BRONZE(5, "bronze");     

  private int weight;
  private String description;

  private Item(int weight, String description) {
    this.weight = weight ;
    this.description = description ;
  }

  // rest of code

}

Long story short
In your code GOLD(2, "gold") can be read as GOLD = new Item(2, "gold") , so the compiler doesn't find the appropriate constructor.

More complete answer and examples
Don't forget that everything (well, almost everything, there are some primitive like int or boolean ) is an object in Java. And so, items of your enum are also objects, and need to be instantiate with a constructor.
Keep in mind that there is an implicit parameterless constructor if you don't provide an explicit constructor.

public enum Test {
  A, B, C;
}

public enum Test2 {
  A, B, C;

  private int value ;

  private Test2(){
    value = 0;
  }
}

public enum Test3 {
  A(1), B(2), C(3);
}

public enum Test4 {
  A, B, C;

  public Test4(int value) {}
}

Test and Test2 are valid, because there is a parameterless constructor (implicit for Test ). But Test3 and Test4 try to instantiate A , B and C with a constructor which doesn't exist.

You need to define an appropriate constructor:

private Item(int weight, String description) {
    this.weight = weight;
    this.description = description;
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM