Showing posts with label Cloning. Show all posts
Showing posts with label Cloning. Show all posts

Thursday, 11 May 2017

Java Object Cloning

Object Cloning in Java

clone is an exact copy of the original. In java, it essentially means the ability to create an object with similar state as the original object. The clone() method provides this functionality.

The java.lang.Cloneable interface must be implemented by the class whose clone object wants to create. If Cloneable interface is not implemented, clone() method generates CloneNotSupportedException.

protected Object clone() throws CloneNotSupportedException  

Facts about cloning

By default, java cloning is ‘field by field copy’ i.e. as the Object class does not have idea about the structure of class on which clone() method will be invoked. So, JVM when called for cloning, do following things:

1) If the class has only primitive data type members then a completely new copy of the object will be created and the reference to the new object copy will be returned.

2) If the class contains members of any class type then only the object references to those members are copied and hence the member references in both the original object as well as the cloned object refer to the same object.

Facts behind cloning

1) You must implement Cloneable interface.
2) You must override clone() method from Object class. [Its weird. clone() method should have been in Cloneable interface.]

/*
Creates and returns a copy of this object. The precise meaning of "copy" may depend on the class of the object.
The general intent is that, for any object x, the expression:
1) x.clone() != x will be true
2) x.clone().getClass() == x.getClass() will be true, but these are not absolute requirements.
3) x.clone().equals(x) will be true, this is not an absolute requirement.
*/
protected native Object  [More ...] clone() throws CloneNotSupportedException;

1. First statement guarantees that cloned object will have separate memory address assignment.
2. Second statement suggests that original and cloned objects should have same class type, but it is not mandatory.
3. Third statement suggests that original and cloned objects should have be equal using equals() method, but it is not mandatory.

public class Employee implements Cloneable {

       private int empoyeeId;
       private String employeeName;
       private Department department;

       public Employee(int id, String name, Department dept) {
              this.empoyeeId = id;
              this.employeeName = name;
              this.department = dept;
       }
      
       /** Shallow copy. */
       /*@Override
       protected Object clone() throws CloneNotSupportedException {
              return super.clone();
       }*/
      
       /** Deep copy. */
       @Override
       protected Object clone() throws CloneNotSupportedException {
           Employee cloned = (Employee)super.clone();
           cloned.setDepartment((Department)cloned.getDepartment().clone());
           return cloned;
       }

       /** setters and getters. */
}

public class Department {
       private int id;
       private String name;

       public Department(int id, String name) {
              this.setId(id);
              this.setName(name);
       }

       /** for deep copy. */
       @Override
       protected Object clone() throws CloneNotSupportedException {
              return super.clone();
       }
      /** setters and getters. */
}

public class TestCloning {
        
    public static void main(String[] argsthrows CloneNotSupportedException {
        Department dept = new Department(1, "Human Resource");
        Employee original = new Employee(1, "Admin"dept);
       
        //Lets create a clone of original object
        Employee cloned = (Employee) original.clone();
       
        //Let verify using employee id, if cloning actually workded
        System.out.println(cloned.getEmpoyeeId());


        //Must be true and objects must have different memory addresses
        System.out.println(original != cloned);

        //As we are returning same class; so it should be true
        System.out.println(original.getClass() == cloned.getClass());

        //Default equals method checks for refernces so it should be false.
          If we want to make it true.
        //we need to override equals method in Employee class.
        System.out.println(original.equals(cloned));
    }
}

Wednesday, 10 May 2017

Prototype Design Pattern

This pattern is used when creation of object directly is costly. Prototype Pattern says that cloning of an existing object instead of creating new one and can also be customized as per the requirement.

For example,
Suppose we are doing a sales analysis on a set of data from a database. Normally, we would copy the information from the database, encapsulate it into an object and do the analysis. But if another analysis is needed on the same set of data, reading the database again and creating a new object is not the best idea. If we are using the Prototype pattern then the object used in the first analysis will be cloned and used for the other analysis.





public interface Prototype {
      public abstract Object clone ( );
}

public class ConcretePrototype implements Prototype {
      public Object clone() {
            return super.clone();
      }
}

public class Client {
      public static void main( String arg[] ) {
            ConcretePrototype obj1= new ConcretePrototype ();
            ConcretePrototype obj2 = (ConcretePrototype)obj1.clone();
      }
}

Application:
Session replication from one server to another server.
Generating the GUI having many numbers of similar controls.

Advantage of Prototype Pattern
It reduces the need of sub-classing.
It hides complexities of creating objects.
The clients can get new objects without knowing which type of object it will be.
It lets you add or remove objects at runtime.

Usage of Prototype Pattern
When the classes are instantiated at runtime.
When the cost of creating an object is expensive or complicated.
When you want to keep the number of classes in an application minimum.
When the client application needs to be unaware of object creation and representation.

Monday, 26 October 2015

What are disadvantages of deep cloning using Serialization?

Disadvantages of using Serialization to achieve deep cloning

1. Serialization is more expensive than using object.clone().

2. Not all objects are serializable.

3. Serialization is not simple to implement for deep cloned object.

Tuesday, 20 October 2015

Which copy technique (deep or shallow ) is used by TreeMap clone() method?

TreeMap clone() method
clone() method returns the shallow copy of the TreeMap instance.
Keys and values copied in the new instance of TreeMap (The keys and values themselves are not cloned.)

Thursday, 8 October 2015

Deep Copy using serialization

Serialization is an alternative way for deep copy.

In Serialization, whole object graph into a persistent store and read whole object graph back when needed. This is exactly what you want when you deep copy an object.

Note, when you deep copy through serialization, you should make sure that all classes in the object's graph are serializable.


Advantages

When you implement the deep cloning, the copied object may contain some other object its references are copied recursively in deep copy.

Cyclic dependencies will be a big problem while implementing deep copy. It does implements deep copy implicitly and gracefully handling cyclic dependencies.

Disadvantages

Serialization is more expensive than using object.clone().

Not all objects are serializable (transient variable cannot be cloned).
Related Posts Plugin for WordPress, Blogger...