枚举类
- 枚举类的理解:类的对象只有有限个。确定的,我们称此类为枚举类。
- 当需要定义一组常量的时候,强烈建议使用枚举类
- 如果枚举类中只有一个对象,则可以作为单例模式的实现方式。
如何定义枚举类
方式一(jdk1.5之前):
package com.atguigu.java;
public class EnumTest {
public static void main(String[] args) {
Season season = Season.SPRING;
System.out.println(season);
}
}
class Season{
private final String seasonName;
private Season(String seasonName) {
this.seasonName = seasonName;
}
public static final Season SPRING= new Season("春天");
public static final Season SUMMER= new Season("夏天");
public static final Season AUTUMN= new Season("秋天");
public static final Season WINTER= new Season("冬天");
}
方式二(jdk1.5之之后)使用enum关键字(父类Enum):
方法:values() valueof() tostring()
package com.atguigu.java;
public class EnumTest {
public static void main(String[] args) {
Season season = Season.SPRING;
System.out.println(season.toString());
Season[] seasons = Season.values();//返回枚举类对象数组
for(int i = 0;i < seasons.length;i ++){
System.out.println(seasons[i]);
}
Season winter = Season.valueOf("WINTER");//根据字符串生成枚举对象
System.out.println(winter.getClass());
}
}
enum Season{
SPRING("春天"),
SUMMER("夏天"),
AUTUMN("秋天"),
WINTER("冬天");
private final String seasonName;
private Season(String seasonName) {
this.seasonName = seasonName;
}
}
枚举类实现接口
枚举类实现接口,可以为每个枚举类的对象重写接口中的方法
package com.atguigu.java;
public class EnumTest {
public static void main(String[] args) {
Season[] seasons = Season.values();//返回枚举类对象数组
for(int i = 0;i < seasons.length;i ++){
seasons[i].show();
}
}
}
interface info{
void show();
}
enum Season implements info{
SPRING("春天"){
@Override
public void show() {
System.out.println("春天在哪里");
}
},
SUMMER("夏天"){
@Override
public void show() {
System.out.println("夏天在哪里");
}
},
AUTUMN("秋天"){
@Override
public void show() {
System.out.println("秋天在哪里");
}
},
WINTER("冬天"){
@Override
public void show() {
System.out.println("冬天在哪里");
}
};
private final String seasonName;
private Season(String seasonName) {
this.seasonName = seasonName;
}
}