一、枚举类型作为常量
- package myenum;
- /**
- * @author zzl
- * 简单的枚举作为常量
- */
- public enum Color {
- GREEN,RED,YELLOW;
- public static void main(String[] args) {
- for (Color c : values()) {
- System.out.println("color:"+c);
- }
- }
- }
- //输出
- /**
- color:GREEN
- color:RED
- color:YELLOW
- */
- package myenum;
- /**
- * @author zzl
- * 简单的枚举作为常量
- */
- public enum Color {
- GREEN,RED,YELLOW;
- public static void main(String[] args) {
- for (Color c : values()) {
- System.out.println(c + " position "+c.ordinal());
- }
- }
- }
- //输出结果
- /**
- GREEN position 0
- RED position 1
- YELLOW position 2
- */
二、与swith结合使用
- public enum Color {
- GREEN,RED,YELLOW;
- public static void main(String[] args) {
- Color c = RED;
- switch (c) {
- case RED:
- System.out.println("红色");
- break;
- case GREEN:
- System.out.println("绿色");
- break;
- case YELLOW:
- System.out.println("黄色");
- break;
- default:
- break;
- }
- }
- }
- //输出
- /**
- 红色
- */
三、多态性(在Color中添加抽象方法)
- public enum Color {
- GREEN{
- void description(){
- System.out.println("绿灯行!");
- }
- },RED{
- void description(){
- System.out.println("红灯停!");
- }
- },YELLOW{
- void description(){
- System.out.println("黄灯亮了等一等!");
- }
- };//如果枚举中有方法则左后一个实例以“;”结束
- abstract void description();
- public static void main(String[] args) {
- for (Color c : values()) {
- c.description();
- }
- }
- }
- <pre name="code" class="java">//输出
- /**
- 绿灯行!
- 红灯停!
- 黄灯亮了等一等!
- */
四、利用构造器为实例添加描述
- public enum ColoStructure {
- GREEN("绿色"),RED("红色"),YELLOW("黄色");//如果枚举中有方法则左后一个实例以“;”结束
- public String description;
- private ColoStructure(String des){
- this.description = des;
- }
- public static void main(String[] args) {
- for (ColoStructure c : values()) {
- System.out.println(c.description);
- }
- }
- }
- <pre name="code" class="java"><pre name="code" class="java">//输出
- /**
- 绿色
- 红色
- 黄色
- */