Enum 枚举基础

1 定义一个枚举

enum Weekend {

    Monday,

    Tuesday,

    Wednesday,

    Thursday,

    Friday,

    Saturday,

    Sunday

}

 

 

2 得到每个枚举值

 for (Weekend weekend : Weekend.values())

 

3 返回枚举在集合中顺序(从0开始)

public final int ordinal() {

    return ordinal;

}

 

4 当前枚举名字

public final String name() {

    return name;

}

 

 

5 根据名字返回相应的enum实例

public static <T extends Enum<T>> T valueOf(Class<T> enumType,

                                            String name) {

    T result = enumType.enumConstantDirectory().get(name);

    if (result != null)

        return result;

    if (name == null)

        throw new NullPointerException("Name is null");

    throw new IllegalArgumentException(

        "No enum constant " + enumType.getCanonicalName() + "." + name);

}

 

 

6 怎么使用枚举

enum Weekend {

    Monday,

    Tuesday,

    Wednesday,

    Thursday,

    Friday,

    Saturday,

    Sunday

}



public class AppTest {

    Weekend weekend;



    public AppTest(Weekend weekend) {

        this.weekend = weekend;

    }



    public String toString() {

    return "the day is " + weekend;

    }



    public static void main(String[] args) {

        System.out.println(new AppTest(Weekend.Monday));

        System.out.println(new AppTest(Weekend.Tuesday));

        System.out.println(new AppTest(Weekend.Wednesday));

    }

}

 

7 枚举不能被继承(下面的代码报错,提示不能从final的test.Weekday继承)

enum WeekendSon extends Weekend {



}

 

 

8 定义enum构造函数

enum Step {
  // Instances must be defined first, before methods: First("this is the first step"), Second("this is the second step"), Third("this is the third step"), Fourth("this is the fourth step"); private String description; public String getDescription() { return description; } Step(String description) { this.description = description; } } public class AppTest { public static void main(String[] args) { for (Step step : Step.values()) { System.out.println(step + ":" + step.getDescription()); } } }

 

输出结果:

First:this is the first step

Second:this is the second step

Third:this is the third step

Fourth:this is the fourth step

 

你可能感兴趣的:(enum)