java – Object. What is this farm by farm copy done by clone()?
In effective Java, the author points out that:
What I want to know is his meaning of copying scene by scene Does this mean that if the class has x bytes in memory, it will only copy a piece of memory? If so, can I assume that all value types of the original class will be copied to the new object?
class Point implements Cloneable{ private int x; private int y; @Override public Point clone() { return (Point)super.clone(); } }
If object Clone () is a copy of the field of the point class. I would say that I don't need to explicitly copy the fields X and y, because the code shown above will be enough for one clone of the point class That is, the following codes are redundant:
@Override public Point clone() { Point newObj = (Point)super.clone(); newObj.x = this.x; //redundant newObj.y = this.y; //redundant }
Am I right?
I know that the reference of the cloned object will automatically point to the location pointed to by the reference of the original object. I'm just not sure that it is specific to the value type If someone can clearly explain object Clone () algorithm specification (simple language), that would be great
Solution
Yes, a field copied by field means that when it creates a new (cloned) object, the JVM copies the value of each field from the original object to the cloned object Unfortunately, this means you have a shallow copy If you want a deep copy, you can override the cloning method
class Line implements Cloneable { private Point start; private Point end; public Line() { //Careful: This will not happen for the cloned object SomeGlobalRegistry.register(this); } @Override public Line clone() { //calling super.clone is going to create a shallow copy. //If we want a deep copy,we must clone or instantiate //the fields ourselves Line line = (Line)super.clone(); //assuming Point is cloneable. Otherwise we will //have to instantiate and populate it's fields manually line.start = this.start.clone(); line.end = this.end.clone; return line; } }
Another important thing about cloning is that the constructor of cloned objects is never called (only copy fields) Therefore, cloning an object does not occur if the constructor initializes an external object or registers the object with some registry
I personally prefer not to use Java cloning Instead, I usually create my own "repeat" method