目录
使用enum定义的枚举类默认继承了Enum类,其可以实现一个或多个接口
使用enum定义非抽象的枚举类时会使用final修饰,因此枚举类不能派生子类
枚举类的构造方法默认且只能使用private访问修饰符
枚举类的所有实例必须在枚举类的类体第一行显示列出,列出的枚举实例默认使用public static final进行修饰
枚举类的默认方法 | 功能 |
public static enumType[ ] values() | 返回一个枚举类型的数组,该数组包含枚举类的所有实例值 |
public static enumType valueOf(String str) | 返回指定名称的枚举实例值 |
- enum Week{
- Monday,Tuesday, Wednesday,Thursday,Friday,Saturday,Sunday
- }
- public class Enum_1 {
- public static void main(String[] args) {
- Week today = Week.Monday;
- System.out.println("today is " + today);
-
- System.out.println("Week枚举类型的所有取值:");
- for (Week week:Week.values()) {
- System.out.println(week);
- }
- }
- }
-
- enum Weeks{
- // 第一行列举枚举实例
- Monday("星期一"),Tuesday("星期二"),Thursday("星期四"),
- Friday("星期五"),Saturday("星期六"),Sunday("星期日");
- private String name;
- Weeks(String name) {
- this.name = name;
- }
- public String toString(){
- return this.name;
- }
- }
-
- public class Enum_2 {
- public static void main(String[] args) {
- Weeks today = Weeks.Monday;
- System.out.println("今天是 " + today);
- System.out.println("Weeks.valueOf('Tuesday') = "+Weeks.valueOf("Tuesday"));
- System.out.println("Week枚举类型的所有取值为:");
- for (Weeks week : Weeks.values()) {
- System.out.println(week);
- }
- }
- }
-
常用方法 | 功能 |
final int ordinal() | 返回枚举实例在枚举类中的序号,计数从0开始 |
final int compareTo(enumtype e) | 用于比较 |
boolean equals(Object object) | 比较两个枚举引用的对象是否相等 |
public String toString() | 返回枚举实例的名称 |
public static enumType valueOf(Class enumType,String name) | 返回指定枚举类型和指定名称的枚举实例值 |
- enum Season{
- // 第一行列举枚举实例
- Spring("春"),Summer("夏"),Fall("秋"),Winter("冬");
- private String name;
- private Season(String name) {
- this.name = name;
- }
- public String toString(){
- return this.name;
- }
- }
-
- public class Enum_3 {
- public static void main(String[] args) {
- System.out.println("Season的所有实例:");
- for (Season season : Season.values()) {
- System.out.println(season);
- }
- System.out.println("————————————————————————————");
-
-
- Season s1 = Season.Spring;
- System.out.println(s1);
- System.out.println("————————————————————————————");
-
-
- Season s2 = Season.valueOf(Season.class,"Summer");
- Season s3 = Season.valueOf("Summer");
- System.out.println(s2 + " ----- " + s2.ordinal());
- System.out.println(s3 + " ----- " + s3.ordinal());
- System.out.println("————————————————————————————");
-
-
- int compare = s2.compareTo(s1);
- if (compare > 0){
- System.out.println(s1 + "------->" + s2);
- }else{
- System.out.println(s2 + "------->" + s1);
- }
- System.out.println("————————————————————————————");
-
-
- if (s2.equals(s1)){
- System.out.println(s1 + " = " + s2);
- }else{
- System.out.println(s1 + " != " + s2);
- }
- System.out.println("————————————————————————————");
- }
- }