需要使用枚举 [英] Need to use Enum

查看:130
本文介绍了需要使用枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很清楚,在java中高级使用枚举。许多将它们与正规课程区分开来并告诉他们需要的要点对我来说也是很清楚的。



任何人都可以为高级枚举的示例代码提供一些实际的例子?哪些可以清楚地阐述


我们应该避免类和
应该使用枚举




请不要混淆。我不是要求使用枚举,还是使用枚举。有很多问题和答案。我正在寻找一些实时/实时/实际的例子,我们应该避免任何其他数据类型或类。

解决方案

尝试< a href =http://download.oracle.com/javase/tutorial/java/javaOO/enum.html =nofollow>此示例:

 公开枚举日{
星期日,星期一,星期四,星期四,
THURSDAY,FREDAY,SATURDAY
}

用法:

  public class EnumTest {
Day day;

public EnumTest(Day day){
this.day = day;
}

public void tellItLikeItIs(){
switch(day){
case MONDAY:System.out.println(星期一不好);
break;

case FRIDAY:System.out.println(星期五更好);
break;

case SATURDAY:
case SUNDAY:System.out.println(周末最好);
break;

默认值:System.out.println(Midweek days are so-so);
break;
}
}

public static void main(String [] args){
EnumTest firstDay = new EnumTest(Day.MONDAY);
firstDay.tellItLikeItIs();
EnumTest thirdDay = new EnumTest(Day.WEDNESDAY);
thirdDay.tellItLikeItIs();
EnumTest fiveDay = new EnumTest(Day.FRIDAY);
fifthDay.tellItLikeItIs();

}
}


I am clear with advanced use of enum in java. Many of the points which differentiate them from regular classes and tells their need are also clear to me.

Can anyone give some practical example with sample code for advanced enum? Which can clearly elaborate about

where we should avoid classes and should use enum instead

.

Please dont be confused. I am not asking for how to use enum or what is the use of enum. There are many questions and answers on this. I am looking for some real time/ live / practical example where we should avoid any other data type or classes.

解决方案

Try this example:

public enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, 
    THURSDAY, FRIDAY, SATURDAY 
}

Usage:

public class EnumTest {
    Day day;

    public EnumTest(Day day) {
        this.day = day;
    }

    public void tellItLikeItIs() {
        switch (day) {
            case MONDAY: System.out.println("Mondays are bad.");
                         break;

            case FRIDAY: System.out.println("Fridays are better.");
                         break;

            case SATURDAY:
            case SUNDAY: System.out.println("Weekends are best.");
                         break;

            default:     System.out.println("Midweek days are so-so.");
                         break;
        }
    }

    public static void main(String[] args) {
        EnumTest firstDay = new EnumTest(Day.MONDAY);
        firstDay.tellItLikeItIs();
        EnumTest thirdDay = new EnumTest(Day.WEDNESDAY);
        thirdDay.tellItLikeItIs();
        EnumTest fifthDay = new EnumTest(Day.FRIDAY);
        fifthDay.tellItLikeItIs();          

    }
}

这篇关于需要使用枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆