There are very good reasons for cloning an object in Java. Consider the following code:
MyObj first = new MyObj(someOwner, someTag, someInt);
MyObj second = first;
In this case, we are simply copying the reference (memory address) of that object. The variables first and second both refer to the same instance of the MyObj class. What the clone() method is supposed to achieve is what is called a deep copy. This is, of course, implementation dependent: the developer of the clone method needs to ensure that a deep copy is actually what is being achieved. So, the code:
MyObj third = (MyObj) first.clone();
What clone() does in this case is go through all of first's instance members and copy/clone those, and uses those values to create an entirely new MyObj instance. It then returns a reference to the new instance, so third is a copy of first, not just a reference to the same instance.
In response to your question in the comments, it depends on your implementation whether or not clone makes new clones of member variables, or simply copies the reference over. Consider the following implementation of the MyObj example class, supposing there also exist classes Person and NameTag. If you clone a MyObj object, you might want the new clone to refer to the same Owner instance as the original, but make a deep copy of the NameTag (this is just an example using imaginary classes, of course). This would represent a one-to-one relationship between MyObj and NameTag instances, and a one-to-many relationship between Owner and MyObj instances. The following code considers both cases mentioned in your question:
class MyObj implements Cloneable {
private Person owner;
private NameTag tag;
private int size;
public MyObj(Person owner, NameTag tag, int size) {
this.owner = owner;
this.tag = tag;
this.size = size;
}
public Object clone() {
MyObj result;
//call all super clone() methods before doing class specific work
//this ensures that no matter where you are in the inheritance heirarchy,
//a deep copy is made at each level.
try {
result = (MyObj) super.clone();
}
catch (CloneNotSupportedException e) {
throw new RuntimeException
("Super class doesn't implement cloneable");
}
//work specific to the MyObj class
result.owner = owner; //We want the reference to the Person, not a clone
result.tag = tag.clone() //We want a deep copy of the NameTag
result.size = size; //ints are primitive, so this is a copy operation
return result;
}