package demo.api;
//最常见枚举类
enum Direction3 {
FRONT, BACK, LEFT, RIGHT;//0,1,2,3...
@Override
public String toString() {
return this.ordinal() + " " + this.name();
}//若不重写,以下输出结果相同:d1, d1.toString(), d1.name()
}
//最复杂的枚举类
enum Direction2 {
//Direction2的对象:含有构造方法,且必须实现抽象方法show()
RIGHT("右") {
@Override
void show() {
System.out.println(getName());
}
}, LEFT("左") {
@Override
void show() {
System.out.println(getName());
}
}, BACK("后") {
@Override
void show() {
System.out.println(getName());
}
}, FRONT("前") {
@Override
void show() {
System.out.println(getName());
}
};
private String name;
private Direction2(String name) {
this.name = name;
}
String getName() {
return name;
}
abstract void show();
}
class 枚举类 {
public static void main(String[] args) {
demo();//最复杂的枚举类演示
// methodDemo();//简单枚举类方法演示
}
//简单枚举类方法演示
private static void methodDemo() {
Direction3 d1 = Direction3.FRONT;
Direction3 d2 = Direction3.BACK;
Direction3 d3 = Direction3.LEFT;
Direction3 d4 = Direction3.RIGHT;
System.out.println(d1);
System.out.println(d1 + "比" + d2 + "大:" + d1.compareTo(d2));
System.out.println(d1 + "的名字是:" + d1.name());
System.out.println(d1 + "序数: " + d1.ordinal());
System.out.println("toString()重写:" + d1.toString());
//从Direction3.class中拿到字节码文件,并从中找到名字为FRONT 的对象返回出来
Direction3 d = Enum.valueOf(Direction3.class, "FRONT");
System.out.println(d.name());
//遍历枚举
System.out.println("遍历枚举:");
Direction3[] direction3s = Direction3.values();//返回枚举对象数组
for (Direction3 dd : direction3s) {
System.out.println(dd.name());
}
}
//最复杂的枚举类演示
private static void demo() {
Direction2 d = Direction2.FRONT;
System.out.println("输出枚举对象: " + d);
System.out.println("枚举对象的自定义方法 : " + d.getName());
System.out.print("枚举对象中的方法: ");
d.show();
//switch语句中的枚举
switch (d) {
case FRONT:
System.out.println("你选择了前");
break;
case BACK:
System.out.println("你选择了后");
break;
case LEFT:
System.out.println("你选择了左");
break;
case RIGHT:
System.out.println("你选择了右");
break;
default:
}
}
}
/**
* //知道枚举的下标,得到枚举的对象和名称
* int idx2 = 2;
* //得到枚举的对象
* Color100[] cs = Color100.values();
* //根据下标得到对象
* Color100 c12 = cs[idx2];
* //得到枚举的名称
* String name = c12.name();
* System.out.println(name);
*/
复杂枚举类
最新推荐文章于 2024-07-14 22:40:26 发布