Skip to content

Instantly share code, notes, and snippets.

@ajaynitt
Last active October 25, 2018 05:04
Show Gist options
  • Save ajaynitt/6891b5f8f95d4c3bd13d6b96a9283053 to your computer and use it in GitHub Desktop.
Save ajaynitt/6891b5f8f95d4c3bd13d6b96a9283053 to your computer and use it in GitHub Desktop.
Cloning of objects in java - normal and faster approach
Cloning is not automatically available to classes. There is some help though, as all Java objects inherit the protected Object clone() method. This base method would allocate the memory and do the bit by bit copying of the object's states.
You may ask why we need this clone method. Can't we create a constructor, pass in the same object and do the copying variable by variable? An example would be (note that accessing the private memberVar variable of obj is legal as this is in the same class):
public class MyObject {
private int memberVar;
...
MyObject(MyObject obj) {
this.memberVar = obj.memberVar;
...
}
...
}
//---------------------------------------------
This method works but object creation with the new keyword is time-consuming. The clone() method copies the whole object's memory in one operation and this is much faster than using the new keyword and copying each variable so if you need to create lots of objects with the same type, performance will be better if you create one object and clone new ones from it. See below a factory method that will return a new object using cloning.
//------------
Now, let's see how to make the Customer object cloneable.
First the Customer class needs to implement the Cloneable Interface.
Override and make the clone() method public, as that is protected in the Object class.
Call the super.clone()method at the beginning of your clone method.
Override the clone() method in all the subclasses of Customer.
//------------------------
public class Customer implements Cloneable {
...
public Object clone() throws CloneNotSupportedException {
Object obj = super.clone();
return obj;
}
}
@ajaynitt
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment