Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java enum giving an error?

Tags:

java

enums

When I try to give a value to my enum, it gives me this error:

constructor status in enum status cannot be applied to given types; STATUS_OPEN(0),

Why is this happening and how do I fix it?

Here is my code thus far:

 public enum Status 
 { 
     STATUS_OPEN(0),  
     STATUS_STARTED(1),  
     STATUS_INPROGRESS(2),  
     STATUS_ONHOLD(3),  
     STATUS_COMPLETED(4),  
     STATUS_CLOSED(5);  

 }

I'm using notepad and the JDK via command prompt - I don't want to use netbeans or eclipse at the moment.

I was following this site: link

I've googled around and I couldn't really find why this issue is occurring or how to fix it by searching for the error.

like image 442
BigBug Avatar asked Jan 12 '12 13:01

BigBug


People also ask

Are enums bad Java?

Java enums are very powerful and important part of the Java language. Even though they can do so much, it is very common to see them either being used incorrectly or not used at all. In this blog post I want to remind you what Java enums can do and show some of the usage patterns that don't get enough attention.

Can you use == for enums Java?

Because there is only one instance of each enum constant, it is permissible to use the == operator in place of the equals method when comparing two object references if it is known that at least one of them refers to an enum constant.

Is there a limit on enums?

An ENUM column can have a maximum of 65,535 distinct elements.


2 Answers

You need to add a constructor to the enum.

public enum Status {
   STATUS_OPEN(0),  
   STATUS_STARTED(1),  
   STATUS_INPROGRESS(2),  
   STATUS_ONHOLD(3),  
   STATUS_COMPLETED(4),
   STATUS_CLOSED(5);

   private final int number;
   Status(int number) { 
       this.number = number;
   }

   public int getMagicNumber() { return number; } 
}

This'll fix your syntax problems, but what are you hoping to achieve with the number? Enums are often used instead of the need for numbers at all.

like image 153
Jeff Foster Avatar answered Oct 09 '22 12:10

Jeff Foster


you need to declare the status instance variable and constructor. like this

public enum Status 
 { 
        STATUS_OPEN(0),  
        STATUS_STARTED(1),  
        STATUS_INPROGRESS(2),  
        STATUS_ONHOLD(3),  
        STATUS_COMPLETED(4),  
        STATUS_CLOSED(5); 

       private int status;

       private Status(int status){
        this.status = status;
       }

     public int getStatus(){
       return this.status;
      } 
 }
like image 29
dku.rajkumar Avatar answered Oct 09 '22 14:10

dku.rajkumar