Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Enum Classes in one Java File

I have 3 String arrays with constants. eg:

 String[] digit = {"one", "two", "three"};
 String[] teen= {"ten", "twenty", "thirty"};
 String[] anchors = {"hundred", "thousand", "million"};

I'm thinking of transferring these to enums separately, so I will have 3 enum classes: digit, teen and anchors with getValue methods implemented. But I don't want to have them in separate files as I have only small data and same type of data. What is the best way to have all these with access methods in same meaningful java file?

like image 983
popcoder Avatar asked Apr 04 '12 19:04

popcoder


People also ask

Can a class have multiple Enums?

java file may have only one public class. You can therefore declare only one public enum in a . java file. You may declare any number of package-private enums.

Can you define multiple Enums inside same class?

Yes, we can define an enumeration inside a class.

Can you have nested Enums?

We can have a nested enum type declaration inside a class, an interface, or another enum type. Nested enum types are implicitly static.

Should Java enum be in a separate file?

An enum is a class and follows same regulations. Having it on its own file is exactly like moving an inner class in a separate file, nothing more nor less. So yes you can move it inside one of the class and be able to access it from outside with OuterClass.


1 Answers

They can be three inner classes like this:

public class Types {
  public enum Digits {...}
  public enum Teens {...}
  ....
}

Then refer them Types.Digits.ONE, Types.Teen.TWENTY etc.

You can also use static imports like this:

import Types.Digits;
import Types.Teen;

..

in order to have shorter references: Digits.ONE, Teen.TWENTY etc.

like image 170
Eugene Retunsky Avatar answered Sep 18 '22 14:09

Eugene Retunsky