您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

JAVA 枚举(enum)详解

2024/3/11 19:44:24发布18次查看
java 枚举是一个特殊的类,一般表示一组常量,比如一年的 4 个季节,一个年的 12 个月份,一个星期的 7 天,方向有东南西北等。
java 枚举类使用 enum 关键字来定义,各个常量使用逗号 , 来分割。
例如定义一个颜色的枚举类。
enum color { red, green, blue; }
以上枚举类 color 颜色常量有 red, green, blue,分别表示红色,绿色,蓝色。
使用实例:
enum color{ red, green, blue;} public class test{ // 执行输出结果 public static void main(string[] args) { color c1 = color.red; system.out.println(c1); }}
执行以上代码输出结果为:
red
内部类中使用枚举
枚举类也可以声明在内部类中:
public class test{ enum color { red, green, blue; } // 执行输出结果 public static void main(string[] args) { color c1 = color.red; system.out.println(c1); }}
执行以上代码输出结果为:
red
每个枚举都是通过 class 在内部实现的,且所有的枚举值都是 public static final 的。
以上的枚举类 color 转化在内部类实现:
class color{ public static final color red = new color(); public static final color blue = new color(); public static final color green = new color();}
迭代枚举元素
可以使用 for 语句来迭代枚举元素:
enum color{ red, green, blue;}public class myclass { public static void main(string[] args) { for (color myvar : color.values()) { system.out.println(myvar); } }}
执行以上代码输出结果为:
red
green
blue
在 switch 中使用枚举类
枚举类常应用于 switch 语句中:
enum color{ red, green, blue;}public class myclass { public static void main(string[] args) { color myvar = color.blue; switch(myvar) { case red: system.out.println("红色"); break; case green: system.out.println("绿色"); break; case blue: system.out.println("蓝色"); break; } }}
执行以上代码输出结果为:
蓝色
values(), ordinal() 和 valueof() 方法
enum 定义的枚举类默认继承了 java.lang.enum 类,并实现了 java.lang.seriablizable 和 java.lang.comparable 两个接口。
values(), ordinal() 和 valueof() 方法位于 java.lang.enum 类中:
values() 返回枚举类中所有的值。ordinal()方法可以找到每个枚举常量的索引,就像数组索引一样。valueof()方法返回指定字符串值的枚举常量。enum color{ red, green, blue;} public class test{ public static void main(string[] args) { // 调用 values() color arr[] = color.values(); // 迭代枚举 for (color col : arr) { // 查看索引 system.out.println(col + " at index " + col.ordinal()); } // 使用 valueof() 返回枚举常量,不存在的会报错 illegalargumentexception system.out.println(color.valueof("red")); // system.out.println(color.valueof("white")); }}
执行以上代码输出结果为:
red at index 0
green at index 1
blue at index 2
red
枚举类成员
枚举跟普通类一样可以用自己的变量、方法和构造函数,构造函数只能使用 private 访问修饰符,所以外部无法调用。
枚举既可以包含具体方法,也可以包含抽象方法。 如果枚举类具有抽象方法,则枚举类的每个实例都必须实现它。
enum color{ red, green, blue; // 构造函数 private color() { system.out.println("constructor called for : " + this.tostring()); } public void colorinfo() { system.out.println("universal color"); }} public class test{ // 输出 public static void main(string[] args) { color c1 = color.red; system.out.println(c1); c1.colorinfo(); }}
执行以上代码输出结果为:
constructor called for : red
constructor called for : green
constructor called for : blue
red
universal color
推荐教程:《java教程》
以上就是java 枚举(enum)详解的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product