public class Main {
public static void main(String[] args) {
/*
时代Java公众号 - N o w J a v a . c o m 提 供
*/
ShallowClone sc = new ShallowClone(100.00);
ShallowClone scClone = (ShallowClone) sc.clone();
// Print the value in original and clone
System.out.println("Original:" + sc.getValue());
System.out.println("Clone :" + scClone.getValue());
// Change the value in original and it will change the value
// for clone too because we have done shallow cloning
sc.setValue(200.00);
// Print the value in original and clone
System.out.println("Original:" + sc.getValue());
System.out.println("Clone :" + scClone.getValue());
}
}
class MyClass implements Cloneable {/*来 自 NowJava.com - 时代Java*/
private double value;
public MyClass(double value) {
this.value = value;
}
public void setValue(double value) {
this.value = value;
}
public double getValue() {
return this.value;
}
public Object clone() {
MyClass copy = null;
try {
// Call the clone() method of the Object class
copy = (MyClass) super.clone();
} catch (CloneNotSupportedException e) {
// If anything goes wrong during cloning, print the error details
e.printStackTrace();
}
return copy;
}
}
class ShallowClone implements Cloneable {
private MyClass holder = new MyClass(0.0);
public ShallowClone(double value) {
this.holder.setValue(value);
}
public void setValue(double value) {
this.holder.setValue(value);
}
/**代码未完, 请加载全部代码(NowJava.com).**/
本文系作者在时代Java发表,未经许可,不得转载。如有侵权,请联系nowjava@qq.com删除。