Java枚举入门

枚举类(掌握)

枚举的诞生历史(了解)

在服装行业,衣服的分类根据性别可以表示为三种情况:男装、女装、中性服装。

private  ?  type;
public void setType(? type){
    this.type = type
}

需求:定义一个变量来表示服装的分类?请问该变量的类型使用什么?
使用int和String类型,且先假设使用int类型,因为分类情况是固定的,为了防止调用者乱创建类型,可以把三种情况使用常量来表示。

public class ClothType {
    public static final int MEN = 0;
    public static final int WOMEN = 1;
    public static final int NEUTRAL = 2;
}

注意:常量使用final修饰,并且使用大小字面组成,如果是多个单词组成,使用下划线分割。
此时调用setType方法传递的值应该是ClothType类中三个常量之一。但是此时依然存在一个问题——依然可以乱传入参数比如100,此时就不合理了。
同理如果使用String类型,还是可以乱设置数据。那么说明使用int或String是类型不安全的。那么如果使用对象来表示三种情况呢?

public class ClothType {
    public static final ClothType MEN =  new ClothType();
    public static final ClothType WOMEN =  new ClothType();
    public static final ClothType NEUTRAL =  new ClothType();
}

此时调用setType确实只能传入ClothType类型的对象,但是依然不安全,为什么?因为调用者可以自行创建一个ClothType对象,如:setType(new ClothType)。
此时为了防止调用者私自创建出新的对象,我们把CLothType的构造器私有化起来,外界就访问不了了,此时调用setType方法只能传入ClothType类中的三个常量。此时代码变成:

public class ClothType {
    public static final ClothType MEN =  new ClothType();
    public static final ClothType WOMEN =  new ClothType();
    public static final ClothType NEUTRAL =  new ClothType();
    private ClothType() {}
} 

高,实在是高!就是代码复杂了点,如果存在定义这种类型安全的且对象数量固定的类的语法,再简单点就更好了——有枚举类。
13.7.2.枚举类的定义和使用(掌握)
枚举是一种特殊的类,固定的一个类只能有哪些对象,定义格式:

public enum  枚举类名{
      常量对象A, 常量对象B, 常量对象C ;
}

我们自定义的枚举类在底层都是直接继承了java.lang.Enum类的。

public enum ClothType {
    MEN, WOMEN, NEUTRAL;
}

枚举中都是全局公共的静态常量,可以直接使用枚举类名调用。

ClothType type = ClothType.MEN;

因为java.lang.Enum类是所有枚举类的父类,所以所有的枚举对象可以调用Enum类中的方法.

String  name = 枚举对象.name();         //  返回枚举对象的常量名称
int ordinal  = 枚举对象.ordinal();  //  返回枚举对象的序号,从0开始

注意:枚举类不能使用创建对象

public class EnumDemo {
    public static void main(String[] args) {
        int ordinal = ClothType.MEN.ordinal();
        String name = ClothType.MEN.name();
        System.out.println(ordinal);
        System.out.println(name);
        new ClothType();    //语法报错
    }
}

目前,会定义枚举类和基本使用就可以了,后面还会讲更高级的使用方式。

若要获得最好的学习效果,需要配合对应教学视频一起学习。需要完整教学视频,请参看https://ke.qq.com/course/272077。

你可能感兴趣的:(Java枚举入门)