17 Enum in Java ?

  • Enum like a special class in java and it’s represent for a group of constant.

    Example:

    1. Define enum tên named Day

    public enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
    }

    2. Use Enum in Java class

    public class EnumExample {
    public static void main(String[] args) {
    Day today = Day.MONDAY;

    switch (today) {
    case MONDAY:
    System.out.println(“Today is Monday!”);
    break;
    case TUESDAY:
    System.out.println(“Today is Tuesday!”);
    break;
    case WEDNESDAY:
    System.out.println(“Today is Wednesday!”);
    break;
    case THURSDAY:
    System.out.println(“Today is Thursday!”);
    break;
    case FRIDAY:
    System.out.println(“Today is Friday!”);
    break;
    case SATURDAY:
    System.out.println(“Today is Saturday!”);
    break;
    case SUNDAY:
    System.out.println(“Today is Sunday!”);
    break;
    }
    }
    }

    3. Enum with methods and fields

    Enums can also contain fields, methods, and constructors just like regular classes

    public enum Day {
    SUNDAY(“Sunday”),
    MONDAY(“Monday”),
    TUESDAY(“Tuesday”),
    WEDNESDAY(“Wednesday”),
    THURSDAY(“Thursday”),
    FRIDAY(“Friday”),
    SATURDAY(“Saturday”);

    private String dayName;

    // Constructor cho enum
    Day(String dayName) {
    this.dayName = dayName;
    }

    // Phương thức getter để lấy tên ngày
    public String getDayName() {
    return dayName;
    }
    }

    public class EnumExample {
    public static void main(String[] args) {
    Day today = Day.MONDAY;

    System.out.println(“Today is ” + today.getDayName());

    // Lặp qua tất cả các giá trị enum
    for (Day day : Day.values()) {
    System.out.println(day + “: ” + day.getDayName());
    }
    }
    }

Leave a Reply

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