枚举类型的概述
什么枚举?
* 枚举指的是在一定范围内取值,这个值必须是枚举类型中的任意一个,而且只能取一个
*
* 枚举的特点:
* 1.必须在规定的范围内取值
* 2.这个值只能取一个
*
* 枚举的本质就是一个类
*
*/
public class EnumDemo01 {
// private int state;
// private GAME2 state;
// private GAME3 state;
private GAME4 state;
public void test() {
// state = GAME.START;
// state = -1;
// state = GAME2.VICTORY;
// state = new GAME2();
// state = GAME3.END;
// state = new GAME3();
// state = -1;
state = GAME4.DEFEAT;
// state = new GAME4();
// state = -1;
}
}
// 版本一
class GAME{
public static final int START = 0x0001;
public static final int END = 0x0002;
public static final int RUNNING = 0x0003;
public static final int STOP = 0x0004;
public static final int VICTORY = 0x0005;
public static final int DEFEAT = 0x0006;
}
// 版本二
class GAME2{
public static final GAME2 START = new GAME2();
public static final GAME2 END = new GAME2();
public static final GAME2 RUNNING = new GAME2();
public static final GAME2 STOP = new GAME2();
public static final GAME2 VICTORY = new GAME2();
public static final GAME2 DEFEAT = new GAME2();
}
// 版本三
class GAME3{
private GAME3() {}
public static final GAME3 START = new GAME3();
public static final GAME3 END = new GAME3();
public static final GAME3 RUNNING = new GAME3();
public static final GAME3 STOP = new GAME3();
public static final GAME3 VICTORY = new GAME3();
public static final GAME3 DEFEAT = new GAME3();
}
// 版本四
enum GAME4{
START, END, RUNNING, STOP, VICTORY, DEFEAT
}
枚举类型成员的特点
枚举既然本质是一个类,那么枚举里面有没有 成员变量,成员方法,构造方法,静态方法,抽象方法? 有的话又有意义吗?
*
* 1.枚举的构造方法必须私有
*
* 2.枚举当中默认有一个私有的无参构造方法,如果你写了一个带参的构造方法,那么会覆盖无参构造方法,所以编译报错
*
* 3.枚举里面的抽象方法是有意义的,其他成员没有意义
*
* 4.枚举的前面必须是枚举的常量成员
*
枚举类型方法
String name() 返回枚举的名称
* int ordinal() 返回枚举的索引
* static <T extends Enum<T>> T valueOf(Class<T> enumType, String name) 返回枚举对象
*
* valueOf(String name) 生成枚举对象
* values() 返回所有的枚举对象的数组
*
* 要求大家能够将枚举的 对象/ 索引 / 名称 进行相互转换
*/
public class EnumDemo04 {
public static void main(String[] args) {
// 获取枚举对象
// Weekend w = Weekend.valueOf(Weekend.class, "MONDAY");
// System.out.println(w);
//
// // 获取枚举对象
// Weekend w2 = Weekend.MONDAY;
// System.out.println(w2);
//
// // 获取枚举对象
// Weekend w3 = Weekend.valueOf("MONDAY");
// System.out.println(w3);
// medhod1();
// method2();
method3();
}