java的枚举基础入门

1.枚举的出现:为了简化代码

2.自定义枚举

public class Practice11 {
    public static void main(String[] args) {
        Week.MON.show();
        Week.TUS.show();
        Week.WED.show();
        System.out.println(Week.MON);
        System.out.println(Week.TUS);
        System.out.println(Week.WED);
    }
}

abstract class Week {
    public final static Week MON = new Week("星期一") {
        public void show() {
            System.out.println("星期一");
        }

    };
    public final static Week TUS = new Week("星期二") {
        public void show() {
            System.out.println("星期二");
        }
    };
    public final static Week WED = new Week("星期三") {
        public void show() {
            System.out.println("星期三");
        }
    };
    private String name;

    public Week(String name) {
        this.name = name;
    }

    public abstract void show();

    @Override
    public String toString() {
        return this.name;
    }

}

 

3.枚举的常用方法

ordinal():从0开始的数字

name():将相应的枚举转换为字符串

4.枚举的使用

public class Practice12 {
    public static void main(String[] args) {
        System.out.println(enum1.MON);
        System.out.println(enum1.TUS);
        System.out.println(enum1.WED);
    }
}

enum enum1 {
    MON, TUS, WED;
}

 

posted @ 2018-07-15 09:16  fatale  阅读(236)  评论(0编辑  收藏  举报