|
Why clone?
Java transmits parameters by passing a handle. When you pass an object, you actually pass an object handle outside the method. Therefore, when you make any changes to the handle in the method, you actually modify the object outside the method. In addition:
Aliasing happens automatically during argument passing. the alias operation is automatically performed during object transmission.
There are no local objects, only local handles. No local object, only local handle
Handles have scopes, objects do not. The handle has a range limit and the object does not
Object lifetime is never an issue in Java. Java, the object lifecycle has never been a problem
There is no language support (e.g. Const) to prevent objects from being modified (to prevent negative effects of aliasing). There is no language guarantee to prevent objects from being modified.
At the same time, Java transmits raw data by value, but references are transmitted for objects. But sometimes we want to have a local object without modifying the external object. This is what we call clone.
Java is a shortest clone by default, that is, a simple clone of objects. However, when a class contains complex objects, such as a school with teacher and student, you need to clone them in depth. To put it simply, from the database perspective, if you want to use "Cascading Delete", you need to use deep cloning; otherwise, it is a shortest clone. An example of deep cloning is as follows:
//: DeepCopy.java// Cloning a composed objectclass DepthReading implements Cloneable { private double depth; public DepthReading(double depth) { this.depth = depth; } public Object clone() { Object o = null; try { o = super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return o; }}class TemperatureReading implements Cloneable { private long time; private double temperature; public TemperatureReading(double temperature) { time = System.currentTimeMillis(); this.temperature = temperature; } public Object clone() { Object o = null; try { o = super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return o; }}class OceanReading implements Cloneable { private DepthReading depth; private TemperatureReading temperature; public OceanReading(double tdata, double ddata){ temperature = new TemperatureReading(tdata); depth = new DepthReading(ddata); } public Object clone() { OceanReading o = null; try { o = (OceanReading)super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } // Must clone handles: o.depth = (DepthReading)o.depth.clone(); o.temperature = (TemperatureReading)o.temperature.clone(); return o; // Upcasts back to Object }}public class DeepCopy { public static void main(String[] args) { OceanReading reading = new OceanReading(33.9, 100.5); // Now clone it: OceanReading r = (OceanReading)reading.clone(); }} ///:~
|