Junior — Middle
Explain the working mechanism of the clone method in Java programming language.
sobes.tech AI
Answer from AI
The clone() method in Java is used to create a copy of an object. It is defined in the Object class and returns a shallow copy of the current object.
To use clone(), a class must:
- implement the
Cloneableinterface, otherwise aCloneNotSupportedExceptionwill be thrown when callingclone(). - override the
clone()method, usually by callingsuper.clone().
Example:
public class Person implements Cloneable {
private String name;
public Person(String name) {
this.name = name;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
It is important to understand that clone() creates a shallow copy: if the object contains references to other objects, only the references are copied, not the nested objects themselves. For deep copying, additional logic needs to be implemented.