Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generalize 3 enums into one type

Tags:

I'm writing a Java program that does some calculations on files. The program supports 3 types of files (documents, images, videos) with each type allowing only few formats:

enum DocType {     pdf, doc, docx, xls, xlsx, ppt, pptx }  enum ImageType {     bmp, jpg, png, gif, ico }  enum VideoType {     avi, mpg, mp4, wmv, mov, flv, swf, mkv } 

In some point in my program, I would like to hold the file extension regardless of the file type, this means that I'd like to be able to do any of the following assignments:

FileType fileExt = DocType.doc FileType fileExt = ImageType.jpg FileType fileExt = VideoType.mp4 

How can I accomplish that behavior in Java? I know enums cannot extend other enums so basically the elegant solution is not possible.

Thanks

like image 469
johni Avatar asked Jan 08 '16 11:01

johni


People also ask

Can you define multiple enums inside same class?

Yes, we can define an enumeration inside a class.

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 enums be nested?

Enums can be defined as members of a class aka 'nested enum types'.

How do you equal enums?

Using Enum. equals() method. equals() method returns true if the specified object is equal to this enum constant.


1 Answers

You can declare an interface that governs them all

interface FileType{ }  enum DocType implements FileType{  PDF // yes, uppercase for constants  ... }  enum ImageType implements FileType{  .... } 

And then you can declare variables of type FileType

FileType file = DocType.PDF; 
like image 89
Sleiman Jneidi Avatar answered Nov 10 '22 07:11

Sleiman Jneidi