Peter Lawrey writes about Two Uses of Enums that most people forget on his blog.
First of all, I hadn't forgotten - I hadn't even realised :)
These approaches are nice and concise - are there any benefits other than conciseness compared with the more traditional ways of achieving the same thing, such as using final
classes with private
constructors for utility classes?
Also, are there any issues (apart from confusing programmers who aren't expecting it)?
Singleton using Enum in Java: By default creation of the Enum instance is thread-safe, but any other Enum method is the programmer's responsibility. You can access it by EasySingleton. INSTANCE, far simpler than calling getInstance() function on Singleton.
It is simple to write Enum Singletons. Enums are inherently serializable. No problems of reflection occur. It is thread-safe to create enum instances.
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.
Enum cannot extend any class in java,the reason is, by default Enum extends abstract base class java. lang. Enum. Since java does not support multiple inheritance for classes, Enum can not extend another class.
It would seem more intuitive to me to use enums
for real enumerations.
I don't really agree with the first use of an enum
from that post. If you want an uninstantiable utility class, just give it a private constructor. It's that simple, and the enum
provides no added benefit in that situation that I see.
The use of enums for singletons in utility classes is great, but I would generally try to keep the fact that an enum
is being used an internal implementation detail. See, for example, Guava's Predicates class which uses an enum
to enforce a single instance of certain Predicate
s like alwaysTrue()
. It does not expose the enum
to users though.
As far as other benefits: yes, there are other benefits such as built-in serializability and absolutely enforcing a single instance of an enum
constant per classloader, even when deserializing.
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