简体   繁体   中英

Why classes in Java are not cloneable by default

In Java, to make a class cloneable, we need to implement Cloneable interface. Implementing this interface, is just to say that this class supports cloning.

But what is the motive of Java language designers for not making "allowed-to-clone" as default functionality of each class?

We have default implementation for shallow copy already present. Then why this restriction ?

Think about cloning an object with nested properties. How deep recursively do you want to go? This could be tough for the memory, so the developers left it for us to decide.

It's a marker interface to let Java know that implementing class is intentionally being designed for cloning (similar use as of other marker interfaces). If you read further, then you find below:

By convention, classes that implement this interface should override Object.clone (which is protected) with a public method. See Object.clone() for details on overriding this method.

You need to provide custom method for cloning. By having the interface Cloneable , Java is aware that you are intentionally supporting cloning of your object. By providing your custom clone method, you are over-ridding the default clone method of the object.

This way, you get the flexibility to decide(Mark) , which objects can be cloned and which not. If clone-able then up to what level(very useful in object graph cases).

Many reasons stand in the way, the chief one being that cloning is not a problem solvable for the general case, much like serialization.

The shallow copy you get by default will in many cases destroy the object's invariants so it is out of the picture as a general, default cloning mechanism.

The "Cloneable" interface is part of a design pattern called a "Marker Class". Basically, within the clone method will be some reference to a type "Cloneable". When you implement the cloneable interface, it means that your class can be referenced as type "Cloneable".

The other reason, in practicality, is that you override the "clone()" method, and clone in your own specific way. That means the data that you deem important is present in the new class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM