枚举类型的引入:
枚举是从java5开始提供的一种新的数据类型,是一个特殊的类,就是固定的多个常量对象的集合。
定义格式:
[修饰]enum 枚举类名
{
常量A,常量B,常量C;
}
代码:
package com.test;enum Weekday
{MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY,SUNDAY;//枚举类的底层构造器为私有的,privare Weekday(){},因此枚举不能创建对象
}
class employee
{private Weekday restday;//一周某天休息public Weekday getResday(){return restday;}public void setResday(Weekday restday) {this.restday = restday;}
}
public class M1001 {public static void main(String[] agrs){employee user=new employee();user.setResday(Weekday.SATURDAY);Weekday restday=user.getResday();if(restday==Weekday.SATURDAY||restday==Weekday.SUNDAY){System.out.println("周末休息");}}
}
枚举类的底层代码,编译后的class文件
java5之后switch支持枚举类型,把类型转换成oridinal(反编译代码中可以看见也就是编译后的class文件)
深入了解枚举类型的操作细节:视频网址