Cloning objects in Java

Using the assignment operator does not create a new object, it only copies the reference to the object. Thus, the two references point to the same area of memory, to the same object. To create a new object with the same state, clone the object is used.

The Object class contains a protected clone() method that performs a bitwise copy of a derived class object. However, you must first override the clone() method as public to be able to call it. In the overridden method, call the base version of the super.clone() method, which does the actual cloning.

To make an object permanently clonable, the class must implement the Cloneable interface. The Cloneable interface contains no methods related to marker interfaces, and its implementation ensures that the clone() method of the Object class will return an exact copy of the object that called it with reproduction of the values of all its fields. Otherwise, the method throws a CloneNotSupportedException exception. Note that when using this mechanism, an object is created without calling the constructor.

This solution is effective only if the fields of the cloned object are values of base types and their wrappers or immutable object types. If the field of the cloned type is a mutable reference type, then a different approach is required for correct cloning. The reason is that when you create a copy of a field, the original and the copy are reference to the same object. In this situation, you should also clone the class field object itself.

Such cloning is possible only if the class attribute type also implements the Cloneable interface and overrides the clone() method. Since, if it is otherwise, the method call is impossible due to its inaccessibility. It follows that if a class has a superclass, then to implement the cloning mechanism of the current descendant class, it is necessary to have a correct implementation of such a mechanism in the superclass. In this case, you should abandon the use of final declarations for fields of object types due to the impossibility of changing their values when implementing cloning.

In addition to the built-in cloning mechanism in Java, you can use the following to clone an object:

  • A specialized copy constructor - the class describes a constructor that takes an object of the same class and initializes the fields of the created object with the values of the fields passed.
  • Factory method, which is a static method that returns an instance of its class.
  • The serialization mechanism is the storage and subsequent restoration of an object to/from a byte stream.

Read also:


Comments

Popular posts from this blog

Methods for reading XML in Java

XML, well-formed XML and valid XML

ArrayList and LinkedList in Java, memory usage and speed