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
-
Oh that ways. But many interviewers ask this question. If there is none, why would Java people allow it? Somewhere may be there is some use, we are not aware about it.benz– benz2013-07-22 16:59:56 +00:00Commented Jul 22, 2013 at 16:59
-
See also: stackoverflow.com/a/14900526/829571assylias– assylias2013-07-22 17:03:27 +00:00Commented Jul 22, 2013 at 17:03
3 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.
13 Comments
java.lang.Math), but I don't think I have ever seen this.enum section of the javadoc, which is not necessarily where you would look for it. A final (for clarity) class + private constructor is IMO the standard idiom for such a use case (although it is functionally equivalent). That is what is typically done in the JDK (including 8).Math is way too old to be an enum.enum you can immediately rest assured that this class satisfies all requirements for utility classes: no subclassing, no instantiation. It is about mental load placed on the programmer. When each piece of project code is blessed with such grace, the overall effect is way beyond subtle.Enum are reference types like class or interfaces. This means you can
well adapt the principle , "program to interface and not implementation".
Comments
Members of an enum is not necessarily fixed till the end of universe. You can add new members without breaking binary comparability. So I can imagine that an enum is created to model some concept which has no instances at the present time but may have some added later.
Is it also possible that an enum is created for a concept that we know definitely will never have any instances? For example enum NegativeNaturalNumber{}? Could it serve any purpose in a program? Who knows, we cannot say with certainty.