Java 枚举和类的区别
枚举
包含一组常量合法的数据,不能创建枚举实例,也不能进行扩展。
1 package com.jtfr.demo; 2 3 public enum Week { 4 MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY , SUNDAY; 5 }
里面默认私有的构造方法,不能用 public 修饰
1 package com.jtfr.demo; 2 3 public enum Week { 4 MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY , SUNDAY; 5 6 Week(){ 7 8 } 9 }
实际上“枚举”的每一个常量都是创建的自身,只是 枚举 自动简化了。
Enum如果有抽象接口,每个常量必须实现接口,这样也说明了,每个常量是创建了对象本身。
1 package com.jtfr.demo; 2 3 public enum Week { 4 MONDAY { 5 @Override 6 void getWeek() { 7 8 } 9 }, TUESDAY { 10 @Override 11 void getWeek() { 12 13 } 14 }, WEDNESDAY { 15 @Override 16 void getWeek() { 17 18 } 19 }, THURSDAY { 20 @Override 21 void getWeek() { 22 23 } 24 }, FRIDAY { 25 @Override 26 void getWeek() { 27 28 } 29 }, SATURDAY { 30 @Override 31 void getWeek() { 32 33 } 34 } , SUNDAY { 35 @Override 36 void getWeek() { 37 38 } 39 }; 40 // 抽象接口必须实现。 41 abstract void getWeek(); 42 }
枚举还可以实现接口
1 package com.jtfr.demo; 2 3 public interface IWeek { 4 void getWeek(); 5 }
1 package com.jtfr.demo; 2 3 public enum Week implements IWeek{ 4 MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY , SUNDAY; 5 6 @Override 7 public void getWeek() { 8 System.out.println("枚举可以实现接口"); 9 } 10 }