Junior — Middle
What is the purpose of the clone() method in the base Object class?
sobes.tech AI
Answer from AI
The clone() method in the Object class is used to create a copy of an object. By default, it performs a shallow copy, meaning it copies the values of the object's fields, but if the fields are references to other objects, only the references are copied, not the objects themselves.
To use clone(), the class must implement the Cloneable interface, otherwise a CloneNotSupportedException will be thrown when calling it.
Example usage:
public class Person implements Cloneable {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
// Usage:
Person p1 = new Person("Ivan", 30);
Person p2 = (Person) p1.clone();
If deep copying is needed, the clone() method should be overridden to copy nested objects.