java枚举:即对java枚举中的例子进行拓展
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java枚举:即对java枚举中的例子进行拓展相关的知识,希望对你有一定的参考价值。
/* 知识点:枚举 枚举是从java5开始提供的一种新的数据类型,是一个特殊的类,就是多个常量对象的集合 定义格式: [修饰符] enum 枚举类名 { 常量A, 常量B, 常量C; } */ //定义枚举 enum Weekday { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday; //枚举类型中的Monday等价于原来的:public static final Weekday Monday = new Weekday(); } class Employees { private Weekday restday; //一周的哪一天休息(数据类型为Weekday) public Weekday getRestday() { return restday; } public void setRestday(Weekday restday) //数据类型为Weekday { this.restday = restday; } } public class EnumerateExample { public static void main(String[] args) { Employees e = new Employees(); //创建员工对象 e.setRestday(Weekday.Wednesday); //通过类名.对象的方式来设置休息时间 Weekday restday = e.getRestday(); //用Weekday类型的变量restday来接收得到的值 if(restday == Weekday.Saturday || restday == Weekday.Sunday) { System.out.println("周末休息..."); } else { System.out.println("周一至周五休息..."); } } } /* Weekday类的字节码文件内容(用java字节码反编译工具进行反编译后查看): final class Weekday extends Enum //自定义的Weekday枚举类在底层里都是继承java.lang中的Enum { public static final Weekday Monday; public static final Weekday Tuesday; public static final Weekday Wednesday; public static final Weekday Thursday; public static final Weekday Friday; public static final Weekday Saturday; public static final Weekday Sunday; private static final Weekday $VALUES[]; public static Weekday[] values() { return (Weekday[])$VALUES.clone(); } public static Weekday valueOf(String s) { return (Weekday)Enum.valueOf(Weekday, s); } private Weekday(String s, int i) { super(s, i); } static { Monday = new Weekday("Monday", 0); Tuesday = new Weekday("Tuesday", 1); Wednesday = new Weekday("Wednesday", 2); Thursday = new Weekday("Thursday", 3); Friday = new Weekday("Friday", 4); Saturday = new Weekday("Saturday", 5); Sunday = new Weekday("Sunday", 6); $VALUES = (new Weekday[] { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }); } } */
以上是关于java枚举:即对java枚举中的例子进行拓展的主要内容,如果未能解决你的问题,请参考以下文章