It's too late to change the question, but more precise would have been to ask "Why does clone() not allow singletons?". A copy()
method would be more convenient.
Is there any reason why enums in Java cannot be cloned?
The manual states that
This guarantees that enums are never cloned, which is necessary to preserve their "singleton" status.
But returning the instance itself would also preserve its status, and I would be able to handle associated enums the same way as other clonable objects.
One may argue that
The general intent [of clone()] is that, for any object x, the expression:
x.clone() != x
will be true, [...]
But for singletons on the contrary I want x.clone() == x
to be true. If the instance itself would be returned, then the singleton pattern would be transparent to referencing objects.
So why are enums not allowed to be cloned or did they forget to think about singletons and immutables, when clone()
was specified?
clone() method guarantees that enums are never cloned, which is necessary to preserve their "singleton" status.
Java Enum clone() Method The clone() method of Enum class throws CloneNotSupportedException. This method ensures that enums cannot be cloned, which helps to maintain their "singleton" property.
We've learned that we can't create a subclass of an existing enum. However, an interface is extensible. Therefore, we can emulate extensible enums by implementing an interface.
Enums are a type and the enum name should start with a capital. Enum members are constants and their text should be all-uppercase.
What's the purpose of cloning a singleton, if x.clone() == x
? Can't you just use x
straight away.
Strictly speaking, if you want to clone something and enforce x.clone() == x
, the only object that can be the result of the clone is x
itself:
def clone() {
return this;
}
Which can be misleading...
If you are designing something and are based on clone()
for differentiation, you are doing it wrong IMHO...
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