Java——枚举
所谓枚举类,就是定义一个类,这个类只能有固定个数的对象,一般用来归纳那些固定类型的事物,比如一年有四季、坦克大战游戏中有四个方向等。Java1.5之后新增了enum关键字用来定义枚举类
1、使用关键字enum定义枚举类
package com.kexin.study;
public class TestEnum {
public static void main(String[] args) {
System.out.println(Season.SPRING.name);
//这样就可以为每个坦克创建一个方向,当按键时通过判断方向来决定动向
Direction direction = Direction.UP;
switch(direction){
case UP:
break;
case DOWN:
break;
case LEFT:
break;
case RIGHT:
break;
}
}
}
/**
* @author KeXin
* 使用enum关键字定义一个枚举类
* 该类的对象只能在类内实例化
*/
enum Season{
//定义四个Season对象
SPRING("spring","flower"),SUMMER("summer","tree"),AUTUM("autum","leaves"),WINTER("winter","snow");
String name,dec;
private Season(String name, String dec) {
this.name = name;
this.dec = dec;
}
}
//定义四个方向
enum Direction{
UP,DOWN,LEFT,RIGHT;
}
enum还提供了一个values()方法,用来获得所用枚举类型:
//使用values获得定义的所有枚举类型
Season[] seasons = Season.values();
for(int i =0;i<seasons.length;i++){
System.out.println(seasons[i].name);
}
2、自定义一个枚举类
自定义个枚举类并不麻烦,需要四个步骤:
- 将属性声明为private final
- 将构造器声明为private,从而只能在类内部实例化对象
- 创建对象后声明为public static final
- 在枚举类之外新建对象赋值为类内对象之一
package com.kexin.study; public class TestMyEnum { public static void main(String[] args) { System.out.println(MyEnum.AUTUMN.getName()); } } class MyEnum{ private final String name,dec; //将属性声明为private final public final static MyEnum SPRING = new MyEnum("spring","flower"); public final static MyEnum SUMMER = new MyEnum("summer","tree"); public final static MyEnum AUTUMN = new MyEnum("autum","leaves"); public final static MyEnum WINTER = new MyEnum("winter","snow"); //将构造器声明为private private MyEnum(String name, String dec) { this.name = name; this.dec = dec; } public String getName() { return name; } public String getDec() { return dec; } @Override public String toString() { return "MyEnum [name=" + name + ", dec=" + dec + "]"; } }
3、枚举类与继承
枚举类同样可以继承接口并重写其方法,不止是普通类的那种重写,还可以为每个枚举类型定制:
interface Show{
public void Show();
}
/**
* @author KeXin
* 使用enum关键字定义一个枚举类
* 该类的对象只能在类内实例化
*/
enum Season implements Show{
//定义四个Season对象
SPRING("spring","flower"){
@Override
public void Show() {
System.out.println("This is spring");
}
},SUMMER("summer","tree"){
@Override
public void Show() {
System.out.println("This is summer");
}
},AUTUM("autum","leaves"){
@Override
public void Show() {
System.out.println("This is autumn");
}
},WINTER("winter","snow"){
@Override
public void Show() {
System.out.println("This is winter");
}
};
String name,dec;
private Season(String name, String dec) {
this.name = name;
this.dec = dec;
}
}