Skip to main content

Java Cloning: Copy Constructors vs. Cloning

Let's run through the pros and cons of Object.clone() and see how it stacks up against copy constructors when it comes to copying objects.

In order to implement cloning, we need to configure our classes and to follow the following steps:
  • Implement the Cloneable interface in our class or its superclass or interface.
  • Define a clone() method that should handle CloneNotSupportedException (either throw or log).
  • And, in most cases from our clone() method, we call the clone() method of the superclass.
Java Cloning versus Copy Constructor
And super.clone() will call it's super.clone() and the chain will continue until the call reaches the clone() method of the Object class, which will create a field by field mem copy of our object and return it back.
Like everything, Cloning also comes with its advantages and disadvantages. However, Java cloning is more famous for its design issues but still, it is the most common and popular cloning strategy present today.

Advantages of Object.clone()

Object.clone(), as mentioned, has many design issues, but it is still the most popular and easiest way of copying objects. Some advantages of using clone() are:
  • Cloning requires much fewer lines of code — just an abstract class with a 4- or 5-line long clone() method, but we will need to override it if we need deep cloning.
  • It is the easiest way of copying objects, especially if we are applying it to an already developed or an old project. We just need to define a parent class, implement Cloneable in it, provide the definition of the clone() method, and we are ready. Every child of our parent will get the cloning feature. 
  • We should use clone to copy arrays because that’s generally the fastest way to do it.
  • As of release 1.5, calling clone on an array returns an array whose compile-time type is the same as that of the array being cloned, which clearly means calling a clone on arrays does not require type-casting.

Disadvantages of Object.clone()

Below are some cons that cause many developers not to use Object.clone():
  • Using the Object.clone() method requires us to add lots of syntax to our code, like implementing a Cloneable interface, defining the clone() method and handling CloneNotSupportedException, and finally, calling Object.clone() and casting it on our object.
  • The Cloneable interface lacks the clone() method. Actually, Cloneable is a marker interface and doesn’t have any methods in it, and we still need to implement it just to tell the JVM that we can perform clone() on our object.
  • Object.clone() is protected, so we have to provide our own clone() and indirectly call Object.clone() from it.
  • We don’t have any control over object construction because Object.clone() doesn’t invoke any constructor.
  • If we are writing a clone method in a child class, e.g. Person, then all of its superclasses should define the clone() method in them or inherit it from another parent class. Otherwise, the super.clone() chain will fail.
  • Object.clone() supports only shallow copying, so the reference fields of our newly cloned object will still hold objects whose fields of our original object was holding. In order to overcome this, we need to implement clone() in every class whose reference our class is holding and then call their clone separately in our clone() method like in the example below.
  • We can not manipulate final fields in Object.clone() because final fields can only be changed through constructors. In our case, if we want every Person object to be unique by id, we will get the duplicate object if we use Object.clone() because Object.clone() will not call the constructor, and final id field can’t be modified from Person.clone().
class City implements Cloneable {
    private final int id;
    private String name;
    public City clone() throws CloneNotSupportedException {
    return (City) super.clone();
    }
}
class Person implements Cloneable {
    public Person clone() throws CloneNotSupportedException {
        Person clonedObj = (Person) super.clone();
        clonedObj.name = new String(this.name);
        clonedObj.city = this.city.clone();
        return clonedObj;
    }
}

Because of the above design issues with Object.clone(), developers always prefer other ways to copy objects like using:
All these options require the use of some external library, plus these libraries will also be using Serialization or Copy Constructors or Reflection internally to copy our object. So if you don’t want to go with the above options or want to write your own code to copy the object, then you can use:
  1.  Serialization 
  2.  Copy constructors 

Serialization

As discussed in 5 different ways to create objects in Java, deserializing a serialized object creates a new object with the same state as in the serialized object. So similar to the above cloning approaches we can achieve deep cloning functionality using object serialization and deserialization as well and with this approach we do not have worry about or write code for deep cloning, we get it by default.

We can do it like it is done below or we can also use other APIs like JAXB which supports serialization.
// Method to deep clone an object using in memory serialization.
public Employee copy(Person original) throws IOException, ClassNotFoundException {
    // First serializing the object and its state to memory using ByteArrayOutputStream instead of FileOutputStream.
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutputStream out = new ObjectOutputStream(bos);
    out.writeObject(original);
    // And then deserializing it from memory using ByteArrayOutputStream instead of FileInputStream,
    // Deserialization process will create a new object with the same state as in the serialized object.
    ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
    ObjectInputStream in = new ObjectInputStream(bis);
    return (Person) in.readObject();
}

However, cloning an object using serialization comes with some performance overhead and we can improve on it by using in-memory serialization if we just need to clone the object and don’t need to persist it in a file for future use, you can read more on How To Deep Clone An Object Using Java In Memory Serialization.

Copy Constructors

This method of copying objects is the most popular among the developer community. It overcomes every design issue of Object.clone() and provides better control over object construction.
public Person(Person original) {
    this.id = original.id + 1;
    this.name = new String(original.name);
    this.city = new City(original.city);
}

Advantages of Copy Constructors Over Object.clone()

Copy constructors are better than Object.clone() because they:
  • Don’t force us to implement any interface or throw an exception, but we can surely do it if it is required.
  • Don’t require any typecasting.
  • Don’t require us to depend on an unknown object creation mechanism.
  • Don’t require parent classes to follow any contract or implement anything.
  • Allow us to modify the final fields.
  • Allow us to have complete control over object creation, meaning we can write our initialization logic in it.
By using the copy constructors strategy, we can also create conversion constructors, which can allow us to convert one object to another object — e.g. The ArrayList(Collection<? extends E> c) constructor generates an ArrayList from any Collection object and copies all items from the Collection object to a newly created ArrayList object.

Popular posts from this blog

ORA-02051 Another Session Or Branch In Same Transaction Failed

ORA-02051 Another Session Or Branch In Same Transaction Failed (Doc ID 2253226.1)          SYMPTOMS for ORA-02051 Another Session Or Branch In Same Transaction Failed. Database performance is slow and caused   the transactions ORA-02051 another session or branch in same transaction failed or finalized CAUSE for ORA-02051 Another Session Or Branch In Same Transaction Failed. Session transactions branches caused the issue Excessive Waits On The Event "Global transaction acquire instance locks" SOLUTION Please use below sql and identified underscore parameter values for ORA-02051 Another Session Or Branch In Same Transaction Failed : SQL> select a.ksppinm "Parameter", b.ksppstvl "Session Value",c.ksppstvl "Instance Value"  FROM x$ksppi a,x$ksppcv b, x$ksppsv c  WHERE a.indx = b.indx AND a.indx = c.indx AND a.ksppinm LIKE '/_%' escape '/'  AND (a.ksppinm like '%clusterwide_global%' or a.ksppinm like '%disable_autotune_...

Video Conferencing Project in Java Source Code

Video Conferencing Project in Java Source Code     ################################################################################# FEATURE ################################################################################# 1.Multi Chat(Used Threadpole) 2.P2P Chat 3.P2P Audio Chat 4.P2P Video Chat 5.Complete Automated 6.H.263 compression Video 7.raw audio PREREQUISITE: 1. JUST INSTALL jmf-2.1.1 e @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ *****/  just need to copy the client side code and run it to a pc   not need any manual IP ***/  How to run : Just run server side code in a PC and then Run Client side code to different  PC.Then the work is done. Server Side Code: ClientListener.java Clients.java Main.java MessageListener.java ServerConstant.java ServerManager.java ServerMonitor.java ServerStatusListener.java   ClientListener.java /*  * To change this template, choose Tools | Templates  * and open the tem...

DBA_SCHEDULER_JOB_RUN_DETAILS and PURGE_LOG

How to purge DBA_SCHEDULER_JOB_RUN_DETAILS? Manually deleting from DBA_SCHEDULER_JOB_RUN_DETAILS is not recommended by oracle.DBA_SCHEDULER_JOB_RUN_DETAILS is a view that is using two master tables (scheduler$_job_run_details and scheduler$_event_log) and display the information about jobs history. As there is one procedure named PURGE_LOG and Oracle have Scheduler for this procedure. It will purges all rows in the job log that are older than 30 days.This is the default behavior of this procedure. You can change this to any number of days you want by setting the attribute "SET_SCHEDULER_ATTRIBUTE". e.g. exec DBMS_SCHEDULER.SET_SCHEDULER_ATTRIBUTE('log_history','15'); It will purge all logs older than 15days and it will maintain the history of 15days. But If you want manually purge these logs, you can use below solution:- exec DBMS_SCHEDULER.PURGE_LOG(log_history => 15, which_log => 'JOB_LOG'); It will purge all entries from the jog log that are o...

JAX-WS Hello World Example – RPC Style

JAX-WS Hello World Example – RPC Style AX-WS is bundled with JDK 1.6, which makes Java web service development easier to develop. This tutorial shows you how to do the following tasks: Create a SOAP-based RPC style web service endpoint by using JAX-WS. Create a Java web service client manually. Create a Java web service client via  wsimport  tool. Create a Ruby web service client. You will be surprise of how simple it is to develop a RPC style web service in JAX-WS. Note In general words, “ web service endpoint ” is a service which published outside for user to access; where “ web service client ” is the party who access the published service. JAX-WS Web Service End Point The following steps showing how to use JAX-WS to create a RPC style web service endpoint. 1. Create a Web Service Endpoint Interface File : HelloWorld.java package com.mkyong.ws ;   import javax.jws.WebMethod ; import javax.jws.WebService ; import javax.jws.soap.SOA...

Oracle character AL32UTF8

The character set determines what languages can be represented in the database. Oracle recommends using Unicode (AL32UTF8) as the database character set. AL32UTF8 is Oracle's name for the UTF-8 encoding of the Unicode standard. The Unicode standard is the universal character set that supports most of the currently spoken languages of the world. The use of the Unicode standard is indispensable for any multilingual technology, including database processing. Changing the database character set is a time consuming and complex project. Therefore, it is very important to select the right character set at installation time. If the language is American English or a Western European language, then the default character set is WE8MSWIN1252. Each Microsoft Windows ANSI Code Page can store data from only one language or a limited group of languages, such as only Western European, or only Eastern European, or only Japanese. AL32UTF8 is a multibyte character set, database operations on character...

ORA-02291: integrity constraint violated - parent key not found

“Error: ORA-02291: integrity constraint violated - parent key not found” Reason:    A Primary key does not have the same value as the foreign key. We will discuss it in detail later in this article. Action:   For  ORA-02291: integrity constraint violated - parent key not found  You may either delete the foreign key or the matching primary key can be added. In either way, you may try to get this error corrected. Let's understand more about ORA-02291: integrity constraint violated - parent key not found? The Oracle software brought us the strength by which multiple tables in the database can pass on information so efficiently. Not only this, there are numerous devices in this software which enables access to and sourcing data from multiple tables. You can easily execute complicated database issues without an unusual uncertainty by creating statements with the fantastic characteristic of this software. Realistically, if we talk about user or database no one is perf...