码迷,mamicode.com
首页 > 其他好文 > 详细

尝试理解枚举

时间:2014-12-21 09:10:00      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:

先模拟一下枚举类:

package enumtest;

public class EnumTest 
{
    public static void main(String[] args) {
        WeekDay day = WeekDay.SUN;
        System.out.println(day.nextDay());
    }
}

//先模拟一个 枚举 (说明白,枚举形成的基本思路)
abstract class WeekDay
{
    private WeekDay(){}  //上来就把它的构造器私有化,因为枚举的实例是固定的
    
    public static final WeekDay MON = new WeekDay(){ //定义(成员)内部类

        @Override
        public WeekDay nextDay() 
        {
            return WeekDay.SUN;
        }
        
    };
    public static final WeekDay SUN = new WeekDay(){

        @Override
        public WeekDay nextDay() 
        {
            return WeekDay.MON;
        }
    };
    
    public abstract WeekDay nextDay();
    
    @Override
    public String toString()
    {
        return this==SUN?"SUN":"MON";
    }
}

Java中的枚举:(jdk1.5以上)

package enumtest;

public class EnumTest 
{
    public static void main(String[] args) {
        WeekDay day = WeekDay.SUN;
        System.out.println(day);
        System.out.println(day.name());
        System.out.println(day.ordinal()); //枚举实例在枚举类中的位置
        System.out.println(day.toString());
        System.out.println(WeekDay.valueOf("MON"));
    }
}

enum WeekDay
{
    SUN,MON(),THU(1),WES,THR,FRI,SAT;
    //构造方法只能私有化
    private WeekDay()
    {
        System.out.println("调用了无参构造器...");
    }  
    private WeekDay(int i)
    {
        System.out.println("调用了有参构造器");
    }
    
}

结果如下:

技术分享

尝试理解枚举

标签:

原文地址:http://www.cnblogs.com/bluechip/p/4176183.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!