Java 枚举
- 一个预定义常量的集合
- 枚举值通常使用大写
- Java中定义的枚举类型都继承
java.lang.Enum
这个类,提供了一些常用方法
- public static T[] values() 返回这个枚举类型所有值数组
- name()
- ordinal() 顺序
简单例子
public enum Day
{
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,THURSDAY, FRIDAY, SATURDAY
}
public static void main(String[] args)
{
System.out.println(Day.FRIDAY instanceof java.lang.Enum); //true
System.out.println(Day.values()); //[Lmyenum.Day;@74a14482
for( Day d : Day.values())
{
System.out.println(d.name());
System.out.println(d.ordinal());
}
}
结果
true
[Lmyenum.Day;@74a14482
SUNDAY
0
MONDAY
1
TUESDAY
2
WEDNESDAY
3
THURSDAY
4
FRIDAY
5
SATURDAY
6
- 定于枚举类型还可以有属性与方法,但必须在枚举常量之后,枚举常量以逗号分隔,封号结尾
- 定义构造函数,若是带参数则需要在枚举常量声明
- 定义抽象函数,必须在枚举常量声明中实现,且每一个枚举常量都将视为一个内部类,无法访问枚举类中的private成员,需要定义为protected
例子
public enum Day
{
SUNDAY(0) //对应构造函数
{
@Override
public int order() //实现抽象函数
{
return this.order;
}
},
MONDAY(1)
{
@Override
public int order()
{
return this.order;
}
}
;
protected final int order; //此处不能用private
Day(int order)
{
this.order = order;
}
public abstract int order(); //抽象函数必须有实现
}
public static void main(String[] args)
{
System.out.println(Day.values());
for( Day d : Day.values())
{
System.out.println(d.name());
System.out.println(d.order());
System.out.println(d.getClass().getName()); //获取class类型
}
}
结果
SUNDAY
0
myenum.Day$1
MONDAY
1
myenum.Day$2
结果
SUNDAY
0
myenum.Day$1
MONDAY
1
myenum.Day$2
从编译结果来看,会生成Day.class Day 1.classDay 2.class
参考
https://docs.oracle.com/javase/7/docs/api/java/lang/Enum.html
https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html
http://stackoverflow.com/questions/18883646/java-enum-methods