Understanding Java Enums: Definition, Syntax, and Examples

使用して回答:GPT-4o-mini によってJava Q&A Hub

質問:

Introduce Java Enums and give examples

回答:

Java Enums (short for enumerations) are a special Java type used to define collections of constants. They are a powerful feature that allows you to define a fixed set of related constants in a type-safe manner. Enums can have fields, methods, and constructors, making them more versatile than simple enumerations in other programming languages.

Basic Syntax

To define an enum in Java, you use the enum keyword followed by the name of the enum and a list of constants. Here’s a simple example:

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

Using Enums

You can use enums in switch statements, as method parameters, or as return types. Here’s an example of how to use the Day enum:

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

        switch (today) {
            case SUNDAY:
                System.out.println("It's Sunday!");
                break;
            case MONDAY:
                System.out.println("It's Monday!");
                break;
            // Add cases for other days...
            default:
                System.out.println("It's a weekday!");
                break;
        }
    }
}

Enums with Fields and Methods

Enums can also have fields, constructors, and methods. Here’s an example of an enum that represents different levels of access:

public enum AccessLevel {
    ADMIN(3), 
    USER(2), 
    GUEST(1);

    private final int level;

    AccessLevel(int level) {
        this.level = level;
    }

    public int getLevel() {
        return level;
    }
}

public class AccessLevelExample {
    public static void main(String[] args) {
        for (AccessLevel access : AccessLevel.values()) {
            System.out.println(access + " has level: " + access.getLevel());
        }
    }
}

Enum with Methods

You can also define methods in enums. Here’s an example that includes a method to check if a day is a weekend:

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

    public boolean isWeekend() {
        return this == SUNDAY || this == SATURDAY;
    }
}

public class WeekendCheck {
    public static void main(String[] args) {
        for (Day day : Day.values()) {
            System.out.println(day + " is weekend: " + day.isWeekend());
        }
    }
}

Summary

Java Enums provide a way to define a set of named constants in a type-safe manner. They can have fields, methods, and constructors, making them a powerful tool for representing fixed sets of related constants. Enums improve code readability and maintainability by providing a clear and structured way to handle constant values.