类的对象是有限个、确定的
package Season;
public class SeasonTest {
public static void main(String[] args) {
season spring = season.SPRING;
season summer = season.SUMMER;
}
}
class season{
//1.声明season对象的属性:用private、final来修饰
private final String seasonName;
private final String seasonDesc;
// 2.私有化类的构造器,并给属性赋值
private season(String seasonName,String seasonDesc){
this.seasonDesc = seasonDesc;
this.seasonName = seasonName;
}
// 3.提供当前枚举类的多个对象 声明为public static final
// static 是为了让其成为类的成员,而不是对象的成员
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("冬天","冰天雪地");
// 4.其他诉求1:获取枚举类对象的属性
public String getSeasonName() {
return seasonName;
}
public String getSeasonDesc() {
return seasonDesc;
}
// 其他诉求2:提供toSring方法
@Override
public String toString() {
return "season [seasonName=" + seasonName + ", seasonDesc=" + seasonDesc + "]";
}
}
定义的枚举类默认继承于java.lang.Enum
主要就是定义类的对象的时候不同,并且要先定义
package Season;
public class SeasonTest1 {
public static void main(String[] args) {
season1 spring = season1.SPRING;
System.out.println(spring);
season1 summer = season1.SUMMER;
}
}
enum season1{
//1.提供当前枚举类的对象,多个对象之间用,隔开,末尾对象;结束
SPRING("春天","春暖花开"),
SUMMER("夏天","夏日炎炎"),
AUTUMN("秋天","秋高气爽"),
WINTER("冬天","冰天雪地");
//1.声明season对象的属性:用private、final来修饰
private final String seasonName;
private final String seasonDesc;
// 2.私有化类的构造器,并给属性赋值
private season1(String seasonName,String seasonDesc){
this.seasonDesc = seasonDesc;
this.seasonName = seasonName;
}
// 4.其他诉求1:获取枚举类对象的属性
public String getSeasonName() {
return seasonName;
}
public String getSeasonDesc() {
return seasonDesc;
}
// 其他诉求2:提供toSring方法
@Override
public String toString() {
return "season1 [seasonName=" + seasonName + ", seasonDesc=" + seasonDesc + "]";
}
}
toString ,就是打印对象的时候的方法
values:看看枚举类中有几个对象
valueOf(String Objname) 返回枚举类中对象名是Objname的对象,如果没有Objname的枚举类对象,则抛异常
public class SeasonTest1 {
public static void main(String[] args) {
season1 spring = season1.SPRING;
System.out.println(spring);
season1 summer = season1.SUMMER;
season1[] values = season1.values();
for(int i = 0; i < values.length; i++){
System.out.println(values[i]);
}
//valueOf(String Objname) 返回枚举类中对象名是Objname的对象,如果没有Objname的枚举类对象,则抛异常
season1 winter = season1.valueOf("WINTER");
System.out.println(winter);
}
}
可以每一个类都实现不同的接口里面的方法。枚举类的对象分别实现接口中的抽象方法
interface info{
void show();
}
enum season1 implements info{
//1.提供当前枚举类的对象,多个对象之间用,隔开,末尾对象;结束
SPRING("春天","春暖花开"){
public void show(){
System.out.println("春天");
}
},
SUMMER("夏天","夏日炎炎"){
public void show(){
System.out.println("宁夏");
}
},
AUTUMN("秋天","秋高气爽"){
public void show(){
System.out.println("秋天啊秋天");
}
},
WINTER("冬天","冰天雪地"){
public void show(){
System.out.println("冬天啊冬天");
}
};