定义枚举类:方式一:(自定义枚举类)
package com.Demo.enum1;
public class SeasonTest1 {
public static void main(String[] args) {
//私有构造器不能创建对象
// Season season = new Season();
Season spring = Season.SPRING;
Season summer = Season.SUMMER;
System.out.println(spring+","+summer);
}
}
//自定义枚举类
class Season{
//1、声明season属性
private final String seasonName;
private final String seasonDesc;
//2、私有化类的构造器
private Season(String seasonName,String seasonDesc){
this.seasonName=seasonName;
this.seasonDesc=seasonDesc;
}
//3、提供当前枚举类的多个对象
public static final Season SPRING = new Season("春天","春暖花开");
public static final Season SUMMER = new Season("夏天","夏日炎炎");
public String getSeasonName() {
return seasonName;
}
public String getSeasonDesc() {
return seasonDesc;
}
@Override
public String toString() {
return "Season{" +
"seasonName='" + seasonName + '\'' +
", seasonDesc='" + seasonDesc + '\'' +
'}';
}
}
定义枚举类:方式二:(使用enum关键字定义枚举类)
//枚举类
package com.Demo.enum1;
public enum SeasonTest {
SPRING("春天","春暖花开"),SUMMER("夏天","夏日炎炎");
private final String seasonNmae;
private final String seasonDesc;
SeasonTest(String seasonNmae,String seasonDesc) {
this.seasonNmae=seasonNmae;
this.seasonDesc=seasonDesc;
}
public String getSeasonNmae() {
return seasonNmae;
}
public String getSeasonDesc() {
return seasonDesc;
}
/*
@Override
public String toString() {
return "SeasonTest{" +
"seasonNmae='" + seasonNmae + '\'' +
", seasonDesc='" + seasonDesc + '\'' +
'}';
}
*/
}
//测试类
package com.Demo.enum1;
import java.util.Arrays;
public class SeasonTest2 {
public static void main(String[] args) {
SeasonTest spring = SeasonTest.SPRING;
SeasonTest summer = SeasonTest.SUMMER;
System.out.println(spring);
System.out.println(summer);
String seasonNmae = spring.getSeasonNmae();
System.out.println(seasonNmae);
System.out.println(SeasonTest.class.getSuperclass());
SeasonTest[] values = SeasonTest.values();
System.out.println(Arrays.toString(values));
SeasonTest test = SeasonTest.valueOf("SPRING");
System.out.println(test);
}
}