In Java, cloning creates copies of objects, but deep and shallow cloning differ in how they handle object references. Shallow cloning only copies the references, while deep cloning copies the entire object structure. Java’s `Cloneable` interface is used for shallow cloning.
Here’s an example of shallow cloning:
class Example implements Cloneable {
int data;
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
Shallow cloning is faster but can lead to unexpected behavior if the cloned object references shared data. Deep cloning avoids this issue by recursively copying all referenced objects. Choose the right cloning method based on your use case.
Leave a Reply