枚举如何使用?有什么用处? enum
2012-03-14 14:47
295 查看
1.枚举类型更规范,在函数形参定义为枚举类型的时候,只接受枚举类型的常量。比起普通的更安全
枚举类型成员默认被public static final修饰
2.枚举类型的构造方法,作用?
3.五子棋中的枚举类型棋子的定义
使用时,得到黑子的字符串"●"
枚举类型成员默认被public static final修饰
class EnumTest { public static void doit(int val){ //可以接受任何参数 switch(val){ case ConstantsI.Constants_A: System.out.println("ConstantsI.Constants_A"); break; case ConstantsI.Constants_B: System.out.println("ConstantsI.Constants_B"); break; default:break; } } public static void doit(ConstantsE val){ //只接受枚举类型常量,更安全 switch(val){ case Constants_A: //注意这里的写法 不是ConstantsE.Constants_A System.out.println("ConstantsE.Constants_A"); break; case Constants_B: System.out.println("ConstantsE.Constants_B"); break; default:break; } } public static void main(String[] args) { EnumTest.doit(1); EnumTest.doit(ConstantsE.Constants_A); } } interface ConstantsI //一般定义 { public static final int Constants_A = 1; public static final int Constants_B = 2; } enum ConstantsE{ //枚举 Constants_A, Constants_B }
2.枚举类型的构造方法,作用?
class EnumTest { public static void main(String[] args){ System.out.println(ConstantsE.Constants_A.getDescription()); //输出:我是枚举类型A } } enum ConstantsE{ //枚举 Constants_A("我是枚举类型A"), Constants_B("我是枚举类型B"); private String description; private ConstantsE(String _description){ this.description = _description; } public String getDescription(){ return this.description; } }
3.五子棋中的枚举类型棋子的定义
package com.ck.wuziqi; /** * 棋子 * @author Administrator * */ public enum Chessman { /** * 黑、白棋子 */ BLACK("●"),WHITE("○"); //相当于 publi static final Chessman BLACK = new Chessman("●"); private String chessman; private Chessman(String chessman){ this.chessman = chessman; } public String getChessman(){ return this.chessman; } }
使用时,得到黑子的字符串"●"
Chessman.BLACK.getChessman()
相关文章推荐
- 【enum】如何在枚举中定义自定义的方法,并进行使用
- 【enum】如何在枚举中定义自定义的方法,并进行使用
- 我为何要在Android中使用枚举(enum),如何使用?
- 单例模式之使用enum枚举数据类型实现
- java enum(枚举)使用详解 + 总结
- 图文详解GPRS无线打印(什么是GPRS打印机?啥用途?如何使用?)
- 什么是ROC与AUC以及如何使用
- Enum枚举的原理及各种使用方法
- Java - 使用标签库有什么好处?如何自定义JSP标签?
- 使用模板有什么缺点?如何避免?
- 博客园的邮件发送如何做的?使用普通邮件比如QQ邮件等,它对发送的邮件的数量有限制。博客园怎么做的呢?用的什么工具?
- 使用enum枚举数据类型实现多线程中的单例模式
- 正确的使用枚举(Enum)
- 2、(知识篇)枚举Enum的使用
- 【转】什么是抽象类什么是接口两者有什么区别?如何使用它
- PHP安全之魔术引号——什么是魔术引号以及如何使用
- onTouch和onTouchEvent以及onClick的顺序,有什么区别,又该如何使用?
- C#中 什么是接口Interface,以及如何简单使用
- 什么是MACD,如何使用MACD指标(新手必学)
- C语言中的enum(枚举)使用方法