- 枚举概念
把一个事物所有可能的取值一一列举出来。例如:一周有七天,只有七种可能
public enum Weekday{
Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
} - 为什么要用枚举
第一是枚举作为返回类型来讲比较容易操作 第二个就是判断时会更高效 第三就是体现编程人员的专业.这是最主要的.写方法得出的返回值一定不会超出枚举的范围,这样避免了使用其判断时失误而带来的麻烦. - 枚举举例
定义一个新类型,该类型定义的变量指向的值为固定的值。所指对象只能是规定的内容。
1) 创建私有构造方法
2) 定义静态变量
package cn.itheima.day01;
public class Weekday {
/* public enum Weekday{
Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
}
public enum Monday = new Weekday();*/
//1.构建私有的构造方法,不允许随意创建对象
private Weekday(){}
//2.创建允许的对象,只允许有7个值,这五个对象都由自己来创建,
//定义静态变量static 类型Weekday 变量名字 Monday ,它的值是new Weekday();,一般属于常量final
public final static Weekday Monday = new Weekday();
public final static Weekday Tuesday = new Weekday();
public final static Weekday Wednesday = new Weekday();
public final static Weekday Thursday = new Weekday();
public final static Weekday Friday = new Weekday();
public final static Weekday Saturday = new Weekday();
public final static Weekday Sunday = new Weekday();
public Weekday nextDay(){
if(this == Monday){
return Tuesday;
}else if(this == Tuesday){
return Wednesday;
}else if (this == Wednesday){
return Thursday;
}else if(this == Thursday){
return Friday;
}else if(this == Friday){
return Saturday;
}else if(this == Saturday){
return Sunday;
}else{
return Monday;
}
}
//打印每个枚举的值,打印标记信息
public String toString(){
if(this == Monday){
return "Monday";
}else if(this == Tuesday){
return Tuesday+"";
}else if(this == Wednesday){
return "Wednesday";
}else if(this == Thursday){
return "Thursday";
}else if(this == Friday){
return "Friday";
}else if(this == Saturday){
return "Saturday";
}else
return "Sunday";
}
}
主函数
package cn.itheima.day01;
public class TestWeekday {
/**
* @param args
*/
public static void main(String[] args) {
//若要对Weekday赋值,只能取定义好的常量
//Weekday weekday = Weekday.Friday;
Weekday weekday1 = Weekday.Monday;
System.out.println(weekday1);
Weekday weekday2 = Weekday.Thursday;
System.out.println(weekday2);
Weekday weekday3 = weekday2.nextDay();
System.out.println(weekday3);
}
}
/*运行结果
* Monday
* Thursday
* Thursday
* */
“`