Enums

Enums (Перечисления)

Enum definition

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

Enum

public enum Type {
    SCIENCE,
    BELLETRE,
    PHANTASY,
    SCIENCE_FICTION
}

Enum

public class Book {
    private String name;
    private Type bookType;
    private String author;

    public Book(String name, String author, Type type) {
        this.bookType = type;
        this.name = name;
        this.author = author;
    }
}

Enum

public class Program {
    public static void main(String[] args) {
        Book b1 = new Book("War and Peace", "L. Tolstoy", Type.BELLETRE);
        System.out.printf("Book '%s' has a type %s", b1.name, b1.bookType);

        switch (b1.bookType) {
            case BELLETRE:
                System.out.println("Belletre");
                break;
            case SCIENCE:
                System.out.println("Science");
                break;
            case SCIENCE_FICTION:
                System.out.println("Science fiction");
                break;
            case PHANTASY:
                System.out.println("Phantasy");
                break;
        }
    }
}

values(): T[], ordinal(): int,

public enum Type {
    SCIENCE,
    BELLETRE,
    PHANTASY,
    SCIENCE_FICTION
}

values(): T[], ordinal(): int,

public class Program {
    public static void main(String[] args) {
        Type[] types = Type.values();
        for (Type s : types) {
            System.out.println(s);
        }
        System.out.println(Type.BELLETRE.ordinal());
    }
}

Result

SCIENCE
BELLETRE
PHANTASY
SCIENCE_FICTION
1

Special cases

Enum item as few fields

public enum Color {
    RED("#FF0000"), BLUE("#0000FF"), GREEN("#00FF00");
    private String code;

    public Color(String code) {
        this.code = code;
    }

    public String getCode() {
        return code;
    }
}

Enum item as few fields

public class Program {
    public static void main(String[] args) {
        System.out.println(Color.RED.getCode());
        System.out.println(Color.GREEN.getCode());
    }
}

Enum item as Method

public enum Operation {
    SUM {
        public int action(int x, int y) {
            return x + y;
        }
    },
    SUBTRACT {
        public int action(int x, int y) {
            return x - y;
        }
    },
    MULTIPLY {
        public int action(int x, int y) {
            return x * y;
        }
    };

    public abstract int action(int x, int y);
}

Enum item as Method

public class Program {
    public static void main(String[] args) {
        Operation op = Operation.SUM;
        System.out.println(op.action(10, 4));
        op = Operation.MULTIPLY;
        System.out.println(op.action(6, 4));
    }
}