Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the pros and cons between Enum and enum-based class implementation in Java?

Tags:

java

enums

I've recently come across an article discussing the use of an enum-based class implementation in C#, which is quite impressive. The second one here is in Java. However, my colleagues suggest me to use Enum instead.

Could anyone point out any pros and cons using each of them, and when to use it?

like image 295
Duc Tran Avatar asked Dec 20 '13 10:12

Duc Tran


2 Answers

The Java article you quote is from 2001. Back then, Java didn't have enums, and the methods the author describes are what programmers used to do back then to work around Java's deficiency. Java 5 introduced enums in 2004 and now the older patterns are obsolete. So your colleagues are rght: you should use enums.

like image 158
wallenborn Avatar answered Oct 14 '22 08:10

wallenborn


The Java standard enum implementation is already fully class based - you can define any methods, member variables, etc you like inside standard Java enums.

There is an excellent description of this with examples in the official enum documentation:

http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html

Additionally the EnumSet, EnumMap, etc collection classes are extremely powerful and efficient. EnumSet has similar performance to using raw bitfields! You only get access to those classes if you use a proper enum though.

like image 38
Tim B Avatar answered Oct 14 '22 07:10

Tim B