Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the use of creating an enum without instance?

Tags:

java

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

like image 272
benz Avatar asked Jul 22 '13 16:07

benz


People also ask

What is the purpose of using enum?

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.

What is enum most useful in creating?

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.

Do enums have instances?

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.

Why do we need enumeration?

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.


1 Answers

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.

like image 109
Marko Topolnik Avatar answered Sep 23 '22 02:09

Marko Topolnik