Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

What is the best practice for packaging Java enums?

is it separate file for each enum?
having same file for all the enums?

What are the pros and cons ?

share|improve this question

closed as too broad by MichaelT, Snowman, GlenH7, durron597, JB King Nov 4 '15 at 22:54

There are either too many possible answers, or good answers would be too long for this format. Please add details to narrow the answer set or to isolate an issue that can be answered in a few paragraphs.If this question can be reworded to fit the rules in the help center, please edit the question.

First, an overriding rule is that if an enum is public, it must be declared in a file of its own. This is a Java rule that applies to all classes, interfaces, and enums, which cannot be broken.

For non-public enums, you should follow the same rule, except when multiple enums are closely connected.

For example, if you are building an expression processor and declaring an enumeration for an expression sub-type, a binary expression sub-type, and a unary expression sub-type, you may want to group the three enumerations together in a single file.

share|improve this answer
Great explanation. Is there any performance impact? if we have closely connected enums in same class as compared to having each for each enum. – goodspeed Sep 14 '12 at 16:00
@goodspeed Placement of classes/enums/interfaces in files has no performance impact (except possibly a tiny impact on compilation speed that you would not notice anyway). – dasblinkenlight Sep 14 '12 at 16:09
@dasblinkenlight Do you have documentation for proving your second sentence, saying public enums should be placed in it's own file? – Max Sep 8 '14 at 17:19
@Max The rules for enums are not different from rules for other classes: if a class is public, it needs to be in the file at a proper location matching the package name, with the class name matching the file name. – dasblinkenlight Sep 8 '14 at 18:04
@dasblinkenlight Ah, thanks for your information and time. – Max Sep 8 '14 at 20:00

Enums are classes so you should pack them as ordinary classes. If the enum is used in many places inside the package then put it in a single file. If the enum is strongly linked with a class, then put it as a public (or protected) static inner class.

I do not see reasons for placing all the enums in a single file unless they are related.

share|improve this answer
If they are related, you can nest them in one class. public class Pse164884 { public enum Cat { siamese, manx} public enum Dog { bullgog, poodle } } – Ray Tayek Apr 13 '13 at 23:49

Not the answer you're looking for? Browse other questions tagged or ask your own question.