Hi everybody, can I clone my class's object like this. What is the difference between the code in the commented part and which I have written. What I understood is the commented part calls the super.clone() method which returns an Object of the current class. Can I directly create a new object explicitly and return it instead using that code.
It's wrong. Your clone method is not creating a clone, it's just creating a new instance (which will have the default values for all fields). A clone should be a field-by-field copy of the original object. Also, when you override the clone method of a non-final class you should be invoking super.clone() to get the object. If all of your fields are primitives or immutable objects, that's all you need to do. If you have fields that are mutable, you should start with an object returned by super.clone() and then make sure you set the state for the mutable fields.
Implementing Cloneable can be quite tricky.
In the case of your MyClone class, you have primitive fields without any mutable objects, so your clone method just need to return super.clone(). That will return a copy of the original object, including correctly set values for the primitive fields (i.e. int a and int b).
Search for Effective Java Joshua Bloch; that book has a description of the clone() method (and says it is not good design); there used to be a sample chapter on the internet free of charge, which included clone().
Jason Cone wrote:If you have fields that are mutable, you should start with an object returned by super.clone() and then make sure you set the state for the mutable fields.
I think you mean to mention deep cloning by this, because this is what we need to do with mutable objects. But there is certainly a flip in it that the mutable object should also support cloning else you will land up with CloneNotSupportedException.
Heroic work plunger man. Please allow me to introduce you to this tiny ad:
a bit of art, as a gift, that will fit in a stocking