java enum
Posted nedrain
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java enum相关的知识,希望对你有一定的参考价值。
Self-defined Enum
//Season.java
public class Season {
// step1: fields which are private final
private final String seasonName;
private final String seasonDesc;
// step2 : private Constructor
private Season(String seasonName, String seasonDesc){
this.seasonName = seasonName;
this.seasonDesc = seasonDesc;
}
// step3 : create some enum object
public static final Season SPRING = new Season("Spring", "Go hiking");
public static final Season SUMMER = new Season("Summer", "Go swimming");
public static final Season AUTUMN = new Season("Autumn", "Go picking");
public static final Season WINTER = new Season("Winter", "Go skiing");
// step 4: you can have the getter
public String getSeasonName() {
return seasonName;
}
public String getSeasonDesc() {
return seasonDesc;
}
@Override
public String toString() {
return "Season{" +
"seasonName=‘" + seasonName + ‘‘‘ +
", seasonDesc=‘" + seasonDesc + ‘‘‘ +
‘}‘;
}
}
// test
@org.junit.Test
public void testSeasonEnum(){
Season spring = Season.SPRING;
System.out.println(spring.toString()); // Season{seasonName=‘Spring‘, seasonDesc=‘Go hiking‘}
}
And when you use "enum"
public enum SeasonTest1 {
SPRING("Spring", "Go hiking"),
SUMMER("Summer", "Go swimming"),
AUTUMN("Autumn", "Go picking"),
WINTER("Winter","Go skiing");
private final String seasonName;
private final String seasonDesc;
SeasonTest1(String seasonName, String seasonDesc){
this.seasonName = seasonName;
this.seasonDesc = seasonDesc;
}
public String getSeasonName() {
return seasonName;
}
public String getSeasonDesc() {
return seasonDesc;
}
}
The Enum Class
you have to know, when you use "enum", you actually extend Enum class
// values()
SeasonTest1[] values = SeasonTest1.values();
for (SeasonTest1 season : values){
System.out.println(season); // SPRIN SUMMER AUTUMN WINTER
}
以上是关于java enum的主要内容,如果未能解决你的问题,请参考以下文章