Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Có thể định nghĩa enum bên trong method trong Java không?

Enumeration trong Java đại diện cho nhóm hằng số có tên. Tạo enum bằng cú pháp:

enum Days {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}

Có thể định nghĩa enum bên trong class. Nhưng KHÔNG THỂ định nghĩa enum bên trong method. Nếu thử sẽ lỗi compile: "enum types must not be local".

Ví dụ lỗi

public class EnumExample {
    public void sample() {
        enum Vehicles {
            Activa125, Activa5G, Access125, Vespa, TVSJupiter;
        }
    }
}

Lỗi

EnumExample.java:3: error: enum types must not be local
    enum Vehicles {
    ^
1 error

Để dùng enum constant trong method: khai báo enum bên trong class, dùng values() trong method.

Ví dụ đúng

public class EnumerationExample {
    enum Enum {
        Mango, Banana, Orange, Grapes, Thursday, Apple
    }
    
    public void testMethod() {
        Enum constants[] = Enum.values();
        System.out.println("Value of constants: ");
        for (Enum d : constants) {
            System.out.println(d);
        }
    }
    
    public static void main(String args[]) {
        EnumerationExample obj = new EnumerationExample();
        obj.testMethod();
    }
}

Đầu ra

Value of constants:
Mango
Banana
Orange
Grapes
Thursday
Apple