I was reading and implementing scenario's through enum. I figured out we can create an enum
without any instance. What is the practical use of such an Enum
? Secondly Enum
can also implement
an interface, but obviously can't extend a class as it already extends class Enum
. What are practical advantages of creating an Enum
without instances?
Ben
You should use enum types any time you need to represent a fixed set of constants. That includes natural enum types such as the planets in our solar system and data sets where you know all possible values at compile time—for example, the choices on a menu, command line flags, and so on.
Enums are used to create our own data type like classes. The enum data type (also known as Enumerated Data Type) is used to define an enum in Java. Unlike C/C++, enum in Java is more powerful. Here, we can define an enum either inside the class or outside the class.
Enums are very powerful as they may have instance variables, instance methods, and constructors. Each enum constant should be written in capital letters. Every enum constant is by default internally public static final of type Enum declared.
Enumerations make for clearer and more readable code, particularly when meaningful names are used. The benefits of using enumerations include: Reduces errors caused by transposing or mistyping numbers. Makes it easy to change values in the future.
Zero-member enums are actually a utility class idiom used by a certain segment of the Java community (most notably, Peter Lawrey). They are the most concise, and arguably the cleanest way to guarantee that the class may not be instantiated or subclassed.
Naturally, you will not have any instance methods in such an enum; only static ones.
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