Java Enums can have behavior?

前端 未结 7 1393
清酒与你
清酒与你 2021-02-02 16:56

In Java, an Enum can do the great things that Enums do, but can also have methods (behavior and logic). What advantage does that have over using a class using an enum? Simple ex

相关标签:
7条回答
  • 2021-02-02 17:07

    Take a look at java/joda time classes, where enums do hell of a lot of job.

    Here is an example of java.time.Month:

    public enum Month implements TemporalAccessor, TemporalAdjuster {
        JANUARY,
        FEBRUARY,
        MARCH,
        APRIL,
        MAY,
        JUNE,
        JULY,
        AUGUST,
        SEPTEMBER,
        OCTOBER,
        NOVEMBER,
        DECEMBER;
    
        private static final Month[] ENUMS = Month.values();
    
        public static Month of(int month) {
            if (month < 1 || month > 12) {
                throw new DateTimeException("Invalid value for MonthOfYear: " + month);
            }
            return ENUMS[month - 1];
        }
    
        // About a dozen of other useful methods go here 
    
    }
    
    0 讨论(0)
  • 2021-02-02 17:09

    In our project, we're using Enums for a few things, but perhaps most prominently for i18n purposes - each piece of shown text is given an Enum. The Enum class has a String-returning method that inspects the Locale that is being used, and picks the correct translation from a collection of translations on runtime.

    This serves as a dual-purpose - you get code completion from your IDE, and also never forget to translate a string.

    The usage is very simple, to the point that it's almost rendundant to give an example, but here's how one might use the translation-enum

    System.out.println(Translations.GREET_PERSON.trans()+" "+user.getName());
    

    Or, if you want to be fancy, have the Enum accept arguments, which will, with some magic string manipulation, be inserted in a marked position in the translations string

    System.out.println(Translations.GREET_PERSON.trans(user.getName());
    
    0 讨论(0)
  • 2021-02-02 17:10

    Here's a simple example:

    enum RoundingMode {
        UP {
            public double round(double d) {
                return Math.ceil(d);
            }
        },
        DOWN {
            public double round(double d) {
                return Math.floor(d);
            }
        };
    
        public abstract double round(double d);
    }
    
    0 讨论(0)
  • 2021-02-02 17:23

    Because the enum instances are singletons, you can use them in switch statements or with == to check equality.

    0 讨论(0)
  • 2021-02-02 17:25

    I'm not quite sure where the title of the question fits in with the rest of it. Yes, Java enums have behaviour. They can have state too, although it should really, really be immutable state. (The idea of a mutable enum value is pretty scary IMO.)

    An enum in Java is a fixed set of objects, basically. The benefit is that you know that if you have a reference of that type, it's always either null or one of the well-known set.

    Personally I really love Java enums and wish C# had them too - they're much more object-oriented than C#'s enums which are basically "named numbers". There are a few "gotchas" in terms of initialization order, but they're generally fab.

    0 讨论(0)
  • 2021-02-02 17:27

    Enum types are also a great way to implement true singletons.

    Classic singleton patterns in Java typically involve private constructors and public static factory methods but are still vulnerable to instantiation via reflection or (de-)serialization. An enum type guards against that.

    0 讨论(0)
提交回复
热议问题