java之枚举类
Posted 爸爸去哪了2之熊猫三胞胎
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java之枚举类相关的知识,希望对你有一定的参考价值。
java之枚举类
枚举类:
使用自定义创建枚举类
public class TestEnum
public static void main(String[] args)
Season season1=Season.SPRING1;
System.out.println(season1);
System.out.println(season1.getSeasonName());
//枚举类
class Season
//1.提供类的属性,声明为private final
private final String seasonName;
private final String seasonDesc;
//声明为final的属性,在构造器中初始化
private Season(String seasonName,String seasonDesc)
this.seasonDesc=seasonDesc;
this.seasonName=seasonName;
//3.通过公共的方法来调用属性
public String getSeasonName()
return seasonName;
public String getSeasonDesc()
return seasonDesc;
@Override
public String toString()
return "Season [seasonName=" + seasonName + ", seasonDesc=" + seasonDesc + "]";
//4.创建枚举类的对象
public static final Season SPRING1=new Season("seasonName1", "seasonDesc1");
public static final Season SPRING2=new Season("seasonName2", "seasonDesc2");
public static final Season SPRING3=new Season("seasonName3", "seasonDesc3");
public static final Season SPRING4=new Season("seasonName4", "seasonDesc4");
使用enum创建枚举类
public class TestEnum
public static void main(String[] args)
Season season1=Season.SPRING1;
System.out.println(season1);
System.out.println(season1.getSeasonName());
//enum中的方法1
System.out.println(Season.values());
for (int i = 0; i < Season.values().length; i++)
System.out.println(Season.values()[i]);
//enum中的方法2 需要传入的是枚举类的名字,否则就会报错
String str="SPRING1";
Season sea=Season.valueOf(str);
System.out.println(sea);
//枚举类
enum Season
//1.创建枚举类的对象
SPRING1("seasonName1", "seasonDesc1"),
SPRING2("seasonName2", "seasonDesc2"),
SPRING3("seasonName3", "seasonDesc3"),
SPRING4("seasonName4", "seasonDesc4");
private final String seasonName;
private final String seasonDesc;
private Season(String seasonName,String seasonDesc)
this.seasonDesc=seasonDesc;
this.seasonName=seasonName;
public String getSeasonName()
return seasonName;
public String getSeasonDesc()
return seasonDesc;
@Override
public String toString()
return "Season [seasonName=" + seasonName + ", seasonDesc=" + seasonDesc + "]";
以上是关于java之枚举类的主要内容,如果未能解决你的问题,请参考以下文章