In order to implement cloning, we need to configure our classes to follow the below steps
- Implement Cloneable interface in our class or its superclass or interface,
- Define clone() method which should handle CloneNotSupportedException (either throw or log),
- And in most cases from our clone() method we call the clone() method of the superclass.
And super.clone() will call its super.clone() and the chain will continue until call will reach to 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 its design issues but still, it is the most common and popular cloning strategy present today.
Advantages of Object.clone()
- Cloning requires very less line of code, just an abstract class with 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 object 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 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 clone on arrays do not require typecasting.
Disadvantages of Object.clone()
Below are some cons due to which many developers don't use Object.clone()- Using Object.clone() method requires us to add lots of syntax to our code like implement Cloneable interface, define clone() method and handle CloneNotSupportedException and finally call to Object.clone() and cast it our object.
- The Cloneable interface lacks clone() method, actually, Cloneable is a marker interface and doesn’t have any method in it and still, we need to implement it just to tell 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 the clone method in a child class e.g. Person then all of its superclasses should define clone() method in them or inherit it from another parent class otherwise super.clone() chain will fail.
- Object.clone() support only shallow copy so reference fields of our newly cloned object will still hold objects which fields of our original object were 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 them separately in our clone() method like in below example.
- 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 objects 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 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
- BeanUtils.cloneBean(object) creates a shallow clone similar to Object.clone().
- SerializationUtils.clone(object) creates a deep clone. (i.e. the whole properties graph is cloned, not only the first level), but all classes must implement Serializable.
- Java Deep Cloning Library offers deep cloning without the need to implement Serializable.
- Serialization
- Copy Constructors
Serialization
As discussed in 5 different ways to create objects in Java, deserialising a serialised object creates a new object with the same state as in the serialized object. So similar to 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 copying object is most popular between developer community it overcomes every design issue of Object.clone() and provides better control over object constructionpublic 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 any exception but we can surely do it if it is required.
- Don’t require any type of cast.
- Don’t require us to depend on an unknown object creation mechanism.
- Don’t require parent class to follow any contract or implement anything.
- Allow us to modify final fields.
- Allow us to have complete control over object creation, we can write our initialization logic in it.
0 comments :
Post a Comment