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
Yes, we can define an enumeration inside a class.
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.
Enums can be defined as members of a class aka 'nested enum types'.
Using Enum. equals() method. equals() method returns true if the specified object is equal to this enum constant.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With