Enum in Java

In Java, an enumeration (also known as an "enum") is a special type of class that represents a fixed set of constants. Each constant is an instance of the enumeration class, and can be accessed using its name.

Here are some features of enumerations in Java:

* Fixed set of constants: The constants defined in an enumeration are fixed at compile-time and cannot be modified at runtime. This makes them useful for defining a set of values that are known ahead of time.

* Type safety: Because each constant in an enumeration is an instance of the enumeration class, the compiler can check that any variable or method parameter of the enumeration type is assigned only one of the constants defined in the enumeration.

* Readability: Enumerations provide a readable and self-documenting way of defining a set of related constants. This makes code using enumerations easier to understand and maintain.

* Enumerations can have constructors, methods, and fields: Enumerations can define their own constructors, methods, and fields, just like regular classes. This allows you to associate behavior and data with the constants defined in the enumeration.


Here is an example of an enumeration in Java:

        
  public enum DayOfWeek {
      MONDAY,
      TUESDAY,
      WEDNESDAY,
      THURSDAY,
      FRIDAY,
      SATURDAY,
      SUNDAY;

      private int dayNumber;

      private DayOfWeek() {
          this.dayNumber = ordinal() + 1;
      }

      public int getDayNumber() {
          return dayNumber;
      }
  }
        
      

In this example, we define an enumeration called DayOfWeek, which contains seven constants representing the days of the week. We also define a constructor that sets a dayNumber field based on the ordinal value of each constant, and a getDayNumber() method that returns this field.

Using this enumeration, we can write code like the following:

        
  DayOfWeek today = DayOfWeek.MONDAY;
  System.out.println("Today is " + today);
  System.out.println("The day number is " + today.getDayNumber());
        
      

This code will output:

        
  Today is MONDAY
  The day number is 1
        
      

Here, we create a variable today of type DayOfWeek, and initialize it to the constant MONDAY. We then print out the name of the constant using its toString() method (implicitly called when concatenating with a string), and the dayNumber field using the getDayNumber() method we defined earlier.