What is the usage of Java enums?

In Java, enums are a special data type used to define a group of constants with fixed values. An enum type can contain zero or more enum constants, with each constant being an instance of that enum type.

The usage of enumeration is as follows:

  1. Define the enumeration type:
  2. Enumeration of the Seasons: SPRING, SUMMER, AUTUMN, WINTER
  3. The above code defines an enumeration type Season, which contains four constant enumerations.
  4. Access enumeration constants:
  5. Season season = Season.SUMMER;
    System.out.println(season); // Output: SUMMER
  6. You can access enum constants by using the enum type name followed by the dot operator.
  7. Utilizing a switch statement:
  8. Season season = Season.SUMMER;
    switch (season) {
    case SPRING:
    System.out.println(“Spring”);
    break;
    case SUMMER:
    System.out.println(“Summer”);
    break;
    case AUTUMN:
    System.out.println(“Autumn”);
    break;
    case WINTER:
    System.out.println(“Winter”);
    break;
    }
  9. Enumerating constants can be used in conjunction with the switch statement to execute the corresponding code block.
  10. Retrieve the name and position of enumerated constants:
  11. Season season = Season.SUMMER;
    System.out.println(season.name()); // Output: SUMMER
    System.out.println(season.ordinal()); // Output: 1
  12. The name() method can be used to obtain the name of an enum constant, and the ordinal() method can be used to obtain the position of an enum constant (counting from 0).
  13. Customizing attributes and methods of enumeration.
  14. The Season enum consists of four constants: SPRING, SUMMER, AUTUMN, and WINTER. Each constant is associated with its corresponding season name in Chinese.
  15. Enumerations can have their own properties and methods, allowing the addition of custom functionalities by including constructors and other methods after the enumeration constants.

In conclusion, enum types offer a more convenient and secure way to represent a set of constant values, and can be used for comparisons, iterations, and other operations.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds