Object Cloning in Java

Discussion in 'Java' started by pradeep, Jul 24, 2007.

  1. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,645
    Likes Received:
    87
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    http://blog.pradeep.net.in
    Objects in Java are referred using reference types, and there is no direct way to copy the contents of an object into a new object.

    The assignment of one reference to another merely creates another reference to the same object. Therefore, a special clone() method exists for all reference types in order to provide a standard mechanism for an object to make a copy of itself. Here are the details you need to know about cloning Java objects.

    Why create a local copy?



    The most probable reason for creating a local copy of an object is because you plan to modify the object, and you don't want to modify the method caller's object. If you decide that you need a local copy, you can perform the operation by using the clone() method of the Object class. The clone() method is defined as protected, but you must redefine it as public in all subclasses that you might want to clone.

    For example, the standard library class ArrayList overrides clone(), so you can call clone() for ArrayList, like this:

    Code:
    import java.util.*;
      class MyInt 
      {
          private int i;
      
      
          public MyInt(int ii) { i = ii; }
      
      
          public void increment() { i++; }
      
      
          public String toString() 
          {
              return Integer.toString(i);
          }
       }
      
      
      public class Test 
      {
          public static void main(String[] args) 
          {
              ArrayList al = new ArrayList(); 
              for(int i = 0; i < 10; i++ )
                  al.add(new MyInt(i));
              
              ArrayList al1 = (ArrayList)al.clone();
              // Increment all al1's elements:
              for(Iterator e = al1.iterator(); e.hasNext(); )
                      ((MyInt)e.next()).increment();
        }
       }
    The clone() method produces an Object, which must be recast to the proper type. This example shows how ArrayList's clone() method does not automatically try to clone each of the objects that the ArrayList contains -- the old ArrayList and the cloned ArrayList are aliased to the same objects. This is often called a shallow copy, since it's only copying the "surface" portion of an object. The actual object consists of this "surface," plus all the objects that the references are pointing to and all the objects those objects are pointing to, etc. This is often referred to as the "Web of objects." When you copy the entire mess, it is called a deep copy.

    The Cloneable interface and deep copies



    By default, classes in Java do not support cloning; the default implementation of the clone() method throws a CloneNotSupportedException. You should override implementation of the clone() method. Remember that you must make it public and, inside the method, your first action must be super.clone(). Classes that want to allow cloning must implement the marker interface Cloneable. Since the default implementation of Object.clone only performs a shallow copy, classes must also override clone to provide a custom implementation when a deep copy is desired. Basically, if you want to make objects of your class publicly cloneable, you need code like this:

    Code:
    class Test implements Cloneable
      {
       ...
          public Object clone()
          {
              try
          {
                  return super.clone();
              }
          catch( CloneNotSupportedException e )
          {
                  return null;
              }
          } 
      ...
      }
    If you are happy with a protected clone, which just blindly copied the raw bits of the object, you don't need to redefine your own version. However, you will usually want a public one. (Note: You can't create a private or default scope clone; you can only increase the visibility when you override.)

    Possible problems and a solution



    Since the clone() method is protected, subclasses have to explicitly agree to be cloneable by overriding this protected method with a public method. All of the Collections classes do this. The subclass also has to implement Cloneable for the default cloning mechanism in Object.clone() to work.

    If you have an object that you know has a public clone() method, but you don't know the type of the object at compile time, you have problems. For instance, say x is declared as an Object. You can't just call x.clone() because Object.clone() is protected. If Cloneable defined a public clone() method, you could use ((Cloneable) x).clone(), but it doesn't. You either have to enumerate all the classes that you think x could be, or you have to resort to reflection.

    Another problem arises when you try deep copying of a complex object. You're assuming that the clone() method of all member object variables also does deep copy; this is too risky of an assumption. You must control the code in all classes, or you must know that all classes involved in deep copy operation do such a copy in the right way.

    One solution to these problems is to clone using serialization. Serialization is usually used to send objects off somewhere (such as into a file or over the network) so that somebody else can reconstruct them later. You can abuse serialization to immediately reconstruct the object yourself. If the object is serializable at all, the reconstruction should be a faithful copy. In normal uses of serialisation, the original object is nowhere near a faithful copy; it could be on the other side of the world at the far end of a network connection. You can be sure that changing the copy will have no effect on the original.
     
    tech nerd likes this.
  2. gautamkhosla29

    gautamkhosla29 New Member

    Joined:
    Jun 16, 2008
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    Good Article...
     
  3. TPrice

    TPrice New Member

    Joined:
    Aug 24, 2010
    Messages:
    9
    Likes Received:
    1
    Trophy Points:
    0
    Thank you very much for this information. I have been confused about the purpose of clones and their appropriate use. I feel that I somewhat understand this function now. I will have to start working with it a little bit so that I can obtain a better grasp of this concept.
     
  4. johnpaulmathew

    johnpaulmathew New Member

    Joined:
    Jul 14, 2011
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    It was a good article.Let me tell you the object cloning ina simple way.In some cases we want to make the duplicate copy of existing objects.In java we have facility for doing this.we call clone() method on that object and create a copy of that object.
     
    Last edited by a moderator: Jul 14, 2011
  5. Tobiasgar

    Tobiasgar New Member

    Joined:
    Aug 29, 2011
    Messages:
    12
    Likes Received:
    0
    Trophy Points:
    0
    Home Page:
    http://www.mspy.com
    Rather simple way of cloning.. thanx)) will know in future:crazy:
     
  6. Lulugreen

    Lulugreen New Member

    Joined:
    May 23, 2011
    Messages:
    13
    Likes Received:
    0
    Trophy Points:
    0
    It is a nice post about Jave. I believe I can learn more from the thread. Thanks!
     
  7. coolzameer3d

    coolzameer3d New Member

    Joined:
    Jun 20, 2012
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    its nice thnx....
     
  8. Jack Hard

    Jack Hard Banned

    Joined:
    Dec 20, 2012
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    Home Page:
    http://www.hitechito.com
    It was a good article.Let me tell you the object cloning ina simple way.In some cases we want to make the duplicate copy of existing objects.In java we have facility for doing this.we call clone() method on that object and create a copy of that object.
     
  9. javaexp

    javaexp New Member

    Joined:
    Mar 26, 2013
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    yes, concept of shallow and deep copy causes issues when we are new to the language. Even when using copy constructors as an, the issues repeat.
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice