下面是枚举简单的使用代码,说明见文中注释 package com.technology.lanxj.enumTest; /** * @author <a href="mailto:nanjifengchen@163.com">LanXJ</a> */ public enum Sex { 男("这个表示的是男性"){ public String toString(){//枚举值“男”自己的方法 return "Boy"; } }, 女("这个表示的是女性");//创建枚举实例时候需要对应该枚举的构造方法 private String info="";//枚举类型可以在枚举值罗列完毕后定义变量 Sex(String info){//枚举类型的私有构造器,枚举不能定义共有构造器 this.info=info; } public String catchInfo(){ return this.info; } private static int getSexTypeCount(){//可以定义自己的方法 return Sex.values().length; } public static Sex getRandomSex(){ int ran=(int)System.currentTimeMillis()%getSexTypeCount(); switch(ran){ case 0:return Sex.男; case 1:return Sex.女; default:return Sex.男; } } public String toString(){//覆盖方法 switch(this){ case 男:return "帅哥"; case 女:return "美女"; default :return "sad"; } } } 以下是引用实例: package com.technology.lanxj.enumTest; /** * @author <a href="mailto:nanjifengchen@163.com">LanXJ</a> */ public class EnumTest { public static void main(String[] args) { for (int i = 0; i < 5; i++) { Sex sinstance=Sex.getRandomSex();//随机获得一个 System.out.println(sinstance); System.out.println("INFO:"+sinstance.catchInfo());//通过枚举值的公共方法获取枚举的属性值 try { Thread.sleep(1000); } catch (Exception e) {} } } }