Wednesday, August 5, 2009

Y Cloneable?

We all have heard and quite often implemented and worked with Cloneable interface. Working with it quite recently encountered something that easily gets ignored while reading about Cloneable. Delving a bit deeper into it ,I figured out that if we have a basic requirment of creating a shallow copy of our custom class, why not define our own method with the name clone or can even technically override the one from Object's class, without calling the conventional super.clone() statement?

For eg: I have a class called User.

public class User{

private String firstName;

private String lastName;

private int age;

// a constructor to initialize an object

public User(String fName, String lName, int age){//code goes here}


Now if I need to return a clone of this object, I can always define/override the one from object class as

@Override

public Object clone(){

return new User(this.firstName, this.lastName, this.age);
}

My idea is that making your class implement Cloneable does not trigger anything automatic in the jvm. The semantics of this interface make sense, if you call Object's class clone method via super.clone(). Because Object's clone method, first makes a check if the calling class has implemented Cloneable , otherwise throws a checked exception CloneNotSupported. So implementing Cloneable interface for your class is more like adhearing to some java object oriented guidlines, saying that one can clone any object if its class has implemented this interface, else throw an exception. This kind of enforces a restriction on the callers, to carefully make a wise decision before making a clone of the object. But the other thing which comes to my mind is that, if I do not want others to make a copy of my object why would I need to expose a 'clone' like method in my class? This is because if I do not write any clone method in my User class above, compiler will not let you call user.clone() saying that "method clone from type Object is not visible". Then whole point of writing a clone method in my User class and to implement this restriction by throwing CloneNotSupportedException makes an additional exercise.

So the whole point is that if I really want to expose cloning of my objects, making a call to Object's clone would give me a template shallow copy of my object, which I could further extend as per requirment to create a deep copy. And to do so, I need to make my class implement Cloneable, otherwise a call to super.clone() would fail. So override clone whenever you seriosuly need to generate a copy of it.

No comments:

Post a Comment