Enum data type contains fixed set of constants. Enum are static and final implicitly. Points to remember for Enum

  • enum improves type safety
  • enum can be easily used in switch
  • enum can be traversed
  • enum can have fields, constructors and methods
  • enum may implement many interfaces but cannot extend any class because it internally extends Enum class

Example :-

public enum Level { 
  HIGH, 
  MEDIUM, 
  LOW 
}

Constants in the above enum can be refered like this:

Level level = Level.HIGH;

All enum types get a static values() method automatically by the Java compiler. Here is an example of iterating all values of an enum:

for (Level level : Level.values()) { 
  System.out.println(level); 
}

 

Fields and methods can be added to enum. Each constant enum value gets these fields. The field values must be supplied to the constructor of the enum when defining the constants.

public enum Level {
    HIGH  (3),  //calls constructor with value 3
    MEDIUM(2),  //calls constructor with value 2
    LOW   (1)   //calls constructor with value 1
    ; // semicolon needed when fields / methods follow

    private final int levelCode;

    private Level(int levelCode) {
        this.levelCode = levelCode;
    }

    public int getLevelCode() {
        return this.levelCode;
    }
}