public enum Operation { ADD { @Override public int apply(int a, int b) { return a + b; } }, SUBTRACT { @Override public int apply(int a, int b) { return a - b; } };
public abstract int apply(int a, int b); }
使用:
1 2
int result = Operation.ADD.apply(5, 3); // 5 + 3 = 8 System.out.println(result);
(3)遍历枚举值
1 2 3
(Color c : Color.values()) { System.out.println(c); }
输出:
1 2 3
RED GREEN BLUE
(4)枚举类的 valueOf 方法
1 2
Color c = Color.valueOf("RED"); System.out.println(c); // 输出:RED
valueOf("RED") 必须匹配 enum 中的名称(区分大小写)。
如果传入 "red",会抛出 IllegalArgumentException。
4. 枚举实现单例模式(推荐)
枚举是实现单例模式的最佳方式,线程安全、防止反射破坏、防止序列化破坏。
1 2 3 4 5 6 7
public enum Singleton { INSTANCE;
public void doSomething() { System.out.println("Hello, Singleton!"); } }