OBJECT CLONING:
Object cloning is for creating an exact copy of an object, not just creating a new reference variable pointing to it.
The modifications made to the cloned object do not affect the original object whatsoever.
The object.clone() method described below is used for this purpose.
Why cloning?
We know that cloning is the way to create the copy of another object. If we need to create the object similar to the existing one, we can do it by using new keyword and then doing the properties settings , but it will take lots of time for processing , like setting values to the variables. Here comes the benefit of cloning method .Cloning overcome all these and it is very easy to make a copy of object.
Uses:
The clone() method is defined in the Object class, this method used to create a local copy of an object in the obvious event of us wanting to modify the object without modifying the method callers object.
Here are a couple of things you must keep in mind while cloning an object:
- Each class you wish to clone must implement the “Cloneable” interface.
In case it doesn’t, the clone method will throw a “CloneNotSupportedException“.
This interface does not contain any methods.It is just a marker interface.
- The clone() method is defined as protected, but you must redefine it as public in all subclasses that you might want to clone.
- The default implementation of Object.clone() performs a shallow copy.
When a class desires a deep copy (Deep copy means if your object contains references of other objects or collections.)or some other custom behavior, they must perform that in their own clone() method after they obtain the copy from the superclass.
- The return type of clone() method is Object, and needs to be explicitly cast back into the appropriate type.
- Most interfaces and abstract classes in Java do not specify a public clone() method.
As a result, often the only way to use the clone() method is if you know the actual class of an object.
- Actual implementations of List like ArrayList and LinkedList all generally have clone() methods themselves.
Example for Object Cloning:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
package com.j2eereference.coreJave; public class BookClone implements Cloneable{ private String name; private int cost; public BookClone(String name, int cost){ this.name = name; this.cost=cost; } public Object clone(){ try{ BookClone cloned = (BookClone)super.clone(); return cloned; } catch(CloneNotSupportedException e){ System.out.println(e); return null; } } public String toString(){ return "[name=" + name+ ",cost=" + cost+ "]"; } public static void main(String[] args){ BookClone book = new BookClone("Java for Dummies", 500); BookClone book1 = (BookClone)book.clone(); System.out.println("BookCloneOriginal=" + book); System.out.println("ClonedCopy=" + book1); } } |
Output:
BookCloneOriginal=[name=Java for Dummies,cost=500]
ClonedCopy=[name=Java for Dummies,cost=500]