枚举

一.枚举

在JDK1.5 之前,我们定义常量都是: public static final.... 。现在好了,有了枚举,可以把相关的常量分组到一个枚举类型里,而且枚举提供了比常量更多的方法。 

public class Season {
    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("冬天","白雪皑皑");

    private String name;
    private String des;
    private Season(){};

    private Season(String name, String des) {
        this.name = name;
        this.des = des;
    }

    @Override
    public String toString() {
        return "Season{"+
                "des='"+des+'\''+
                ", name='"+name+'\''+
                '}';
    }
}

版本迭代以后

1.构造器默认私有

2.枚举中属性必须位于枚举元素下面

3.所有的自定义枚举默认继承自Enum类

public enum Season {
    SPRING("春天","穿暖花开"),
    SUMMER("夏天","烈日炎炎"),
    AUTUMN("秋天","天高云阔"),
    WINTER("冬天","白雪皑皑");

    private String name;
    private String des;
    Season(){};

    Season(String name, String des) {
        this.name = name;
        this.des = des;
    }
    
}

也可以直接建立一个Enum类型

public enum Gender {
    MAN,WOMAN
}

main

public class EnumTest {
    public static void main(String[] args) {
        Gender gender=Gender.MAN;
        switch (gender){
            case MAN:
                System.out.println("just man");
                break;
            case WOMAN:
                System.out.println("just woman");
                break;
            default:
                throw new IllegalStateException("Unexpected value: " + gender);
        }
    }
}

即可

上一篇:Mean Shift(均值漂移)原理及在视频跟踪中的使用


下一篇:Vue2中使用vue-awesome-swiper3(对应swiper4)