Java中如何克隆一个对象?
在Java中,克隆一个对象通常涉及实现Cloneable
接口并重写clone()
方法。以下是一个简单的例子:
public class MyClass implements Cloneable {
private int value;
public MyClass(int value) {
this.value = value;
}
// Getter and Setter
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
// Clone method
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
// Main method for demonstration
public static void main(String[] args) {
try {
MyClass original = new MyClass(10);
MyClass clone = (MyClass) original.clone();
// Check that the clone is independent of the original
System.out.println(original.getValue()); // Output: 10
System.out.println(clone.getValue()); // Output: 10
// Modify the value of the clone
clone.setValue(20);
// Check that the original object is not affected
System.out.println(original.getValue()); // Output: 10
System.out.println(clone.getValue()); // Output: 20
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}
在这个例子中,MyClass
实现了Cloneable
接口,并重写了clone()
方法。在main
方法中,我们创建了一个MyClass
对象的克隆,并修改了克隆的value
属性,以展示克隆对象是独立于原对象的。
评论已关闭