枚举类

1.什么是枚举类?枚举类的对象声明的修饰符有哪些?
枚举类:类中的对象个数是确定的,有限个
修饰符:public static final

2.如何自定义枚举类?

// 自定义枚举类
class Season {
    //1.声明Season对象的属性:private final修饰
    private final String seasonName;
    private final String seasonDesc;

    //2.私有化类的构造器,并给对象属性赋值
    private Season(String seasonName, String seasonDesc) {
        this.seasonName = seasonName;
        this.seasonDesc = seasonDesc;
    }

    //3.提供当前枚举类的多个对象:public static final修饰的
    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.获取枚举类对象的属性
    public String getSeasonName() {
        return seasonName;
    }

    public String getSeasonDesc() {
        return seasonDesc;
    }

    //5.提供toString()方法
    @Override
    public String toString() {
        return "Season{" +
                "seasonName='" + seasonName + '\'' +
                ", seasonDesc='" + seasonDesc + '\'' +
                '}';
    }
}

3.如何使用enum关键字定义枚举类?

//使用enum关键字定义枚举类
enum Season1 {
    //1.提供当前枚举类的对象,多个对象之间用”,“隔开,末尾对象用”;“结束
    SPRING("春天", "这是春天的描述"),
    SUMMER("夏天", "这是夏天的描述"),
    AUTUMN("秋天", "这是秋天的描述"),
    WINTER("冬天", "这是冬天的描述");

    //2.声明Season对象的属性:private final修饰
    private final String seasonName;
    private final String seasonDesc;

    //3.私有化类的构造器,并给对象属性赋值
    private Season1(String seasonName, String seasonDesc) {
        this.seasonName = seasonName;
        this.seasonDesc = seasonDesc;
    }

    //4.获取枚举类对象的属性
    public String getSeasonName() {
        return seasonName;
    }

    public String getSeasonDesc() {
        return seasonDesc;
    }
}

4.如何让枚举类对象分别实现接口?

interface Info {
    void show();
}

//使用enum关键字定义枚举类
enum Season1 implements Info {
    //1.提供当前枚举类的对象,多个对象之间用”,“隔开,末尾对象用”;“结束
    SPRING("春天", "这是春天的描述") {
        @Override
        public void show() {
            System.out.println("春");
        }
    },
    SUMMER("夏天", "这是夏天的描述") {
        @Override
        public void show() {
            System.out.println("夏");
        }
    },
    AUTUMN("秋天", "这是秋天的描述") {
        @Override
        public void show() {
            System.out.println("秋");
        }
    },
    WINTER("冬天", "这是冬天的描述") {
        @Override
        public void show() {
            System.out.println("冬");
        }
    };

    //2.声明Season对象的属性:private final修饰
    private final String seasonName;
    private final String seasonDesc;

    //3.私有化类的构造器,并给对象属性赋值
    private Season1(String seasonName, String seasonDesc) {
        this.seasonName = seasonName;
        this.seasonDesc = seasonDesc;
    }

    //4.获取枚举类对象的属性
    public String getSeasonName() {
        return seasonName;
    }

    public String getSeasonDesc() {
        return seasonDesc;
    }
}

你可能感兴趣的:(枚举类)