Wednesday, 3 December 2014

ENUM TYPE - DECLARATION ERROR

ENUM is a data type - using which can create a fixed set of constants.

Example:

package enum.example;

class EnumExample { 

  public static void main(String args[]){
     

     //Declaring ENUM here yields compile time error

     public enum Days { MON, TUE, SAT}
     

     for(Days d:Days.values()){
         System.out.println(d);
     }
  }

}


Output:

Compile time error:

Exception in thread "main" java.lang.Error: Unresolved compilation problems:
    The member enum Days can only be defined inside a top-level class or interface
    Days cannot be resolved to a type
    Days cannot be resolved

 
Because we should include enum declaration inside a method

It's declaration should be inside a top-level class or interface.

so move the enum declaration to class level


package enum.example;

class EnumExample {  


    //Class-level declaration is correct

    public enum Days { MON, TUE, SAT}

    public static void main(String args[]){


     for(Days d:Days.values()){


         System.out.println(d);


     }


 }


}


Output:

MON
TUE
SAT

No comments:

Post a Comment