枚举 Enum 1.7+
- enum 默认继承Object 跟Enum
- enum 里面的枚举值各自只有一份.enum是不能new出来的。
- 会默认一个无参的构造方法,如果自定义一个构造方法,则不会默认创建无参的构造方法。
- 构造方法是private
- 枚举类可以实现接口,但不能被继承和继承别人
(switch中key的值也可以是 byte short int char String enum)
枚举类
1 public enum Day { 2 Monday,Tuesday,Wednesday,Thursday,Friday; 3 }
将对象设置为静态属性,然后将构造方法私有化(只有在本类中才可以new),这样就实现了规定一个类中对象的个数,相当于枚举
public class WeekDay { public static WeekDay Monday=new WeekDay(); public static WeekDay Tuesday=new WeekDay(); public static WeekDay Wednesday=new WeekDay(); public static WeekDay Thursday=new WeekDay(); public static WeekDay Friday=new WeekDay(); private WeekDay(){ System.out.println("无参构造..."); } }
测试类
1 public class Text { 2 3 public static void main(String[] args) { 4 //创建枚举对象的方法1 5 Day day1=Day.Monday; 6 Day day2=Day.Tuesday; 7 8 //创建枚举对象的方法2 9 Day d1=Enum.valueOf(Day.class, "Monday"); 10 11 System.out.println(day1.equals(d1)); 12 13 //创建枚举对象的方法3 14 Day d2=Day.valueOf(Day.class, "Tuesday"); 15 System.out.println(day2.equals(d2)); 16 //名字 17 System.out.println(d2.name()); 18 //下标 19 System.out.println(d2.ordinal()); 20 21 //枚举对象放进数组 22 Day [] d3=Day.values(); 23 24 for (Day day : d3) { 25 System.out.println(day); 26 } 27 28 WeekDay wd=WeekDay.Friday; 29 wd.hashCode(); 30 } 31 32 }