Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are Java enums not clonable?

Tags:

java

clone

enums

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?

like image 419
Christian Strempfer Avatar asked Nov 26 '09 12:11

Christian Strempfer


People also ask

Can enum be cloned?

clone() method guarantees that enums are never cloned, which is necessary to preserve their "singleton" status.

Can we clone enum in Java?

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.

Can enums be subclassed?

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.

Should Java enums be all caps?

Enums are a type and the enum name should start with a capital. Enum members are constants and their text should be all-uppercase.


1 Answers

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...

like image 142
Miguel Ping Avatar answered Nov 09 '22 17:11

Miguel Ping