Java教程

枚举

本文主要是介绍枚举,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

一.枚举

在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);
        }
    }
}

即可

这篇关于枚举的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!