Junior — Middle
Explain the purpose of the clone() method in object-oriented programming.
sobes.tech AI
Answer from AI
The clone() method in object-oriented programming is used to create a copy of an object. It allows obtaining a new object with the same state as the original but with a separate memory area.
In Java, the clone() method is defined in the Object class and is usually overridden to implement deep or shallow copying. Deep copying creates copies of all nested objects, while shallow copying copies only references.
Example of overriding the clone() method:
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone(); // shallow copy
}
Using clone is useful when you need to work with copies of objects without affecting the original.