as I understood, the method clone()
gives us the ability to copy object (no refernce) in Java. But I also read, that the copy is shallow. So what the point? Which a
to clone in depth you have to implement Cloneable and override clone()
public class MyClass implements Cloneable {
private Object attr = new Object();
@Override
public Object clone() throws CloneNotSupportedException {
MyClass clone = (MyClass)super.clone();
clone.attr = new Object();
return clone;
}
@Override
public String toString() {
return super.toString()+", attr=" + attr;
}
public static void main(String[] args) throws Exception {
MyClass x = new MyClass();
System.out.println("X="+x);
MyClass y = (MyClass)x.clone();
System.out.println("Y="+y);
}
}