Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would I use an Enum, and not just a class?

Tags:

java

enums

I was helping a friend with Java the other day, and they were asking about Enums. I explained that the C syntax of (something like)

enumeration Difficulty{
    BEGINNER= 1;
    PRO=5;
    EXPERT = 11;
}

Wasn't the way to go, the Java syntax is something(1); you made a constructor that accepted an int and then did this and that...etc.

But they stopped me and asked "If we're using constructors and so on, why bother with an enum, why not just have a new class?"

And I couldn't answer. So why would you use an enum in this case, and not a class?

like image 688
AncientSwordRage Avatar asked Aug 14 '12 13:08

AncientSwordRage


People also ask

What is the point of using enums?

Enums are used when we know all possible values at compile time, such as choices on a menu, rounding modes, command-line flags, etc. It is not necessary that the set of constants in an enum type stay fixed for all time. A Java enumeration is a class type.

Why is enum preferred?

Conclusion: enum class es should be preferred because they cause fewer surprises that could potentially lead to bugs.

How is enum different from class?

An enum can, just like a class , have attributes and methods. The only difference is that enum constants are public , static and final (unchangeable - cannot be overridden). An enum cannot be used to create objects, and it cannot extend other classes (but it can implement interfaces).

Why enums should not be used?

Enums are good to represent static/singleton objects but should never be used as value objects or have attributes that get set during usage. You can use an enum to 'type/label' a two week duration, but the actual start/end dates should be attributes of a class DateRange.


1 Answers

Enums are strictly limited. It is impossible to define an enum value outside of the specified values (whereas with a class you can invoke new to create a new value).

Enums are also heavily optimized by at least most JVMs, and there are also new classes and language features which take advantage of enums' compactness and speed. For example, there are new classes created, EnumSet and EnumMap, which implement an enum-keyed set or map using a bitset and an array, respectively (which are probably the fastest possible implementations for those abstract data types).

Additionally, enum types can be used in switch statements. If you're pre-Java1.7, this is your best option for customized switch statements (and is still probably superior to using String values because of type safety; mistyping the enum value will cause a compile-time error, but mistyping the string will cause a more insidious runtime error-- or worse, a logic error that you can't understand until you really stare at the code and see the typo).

like image 148
Platinum Azure Avatar answered Sep 28 '22 10:09

Platinum Azure