Junior — Middle
How to implement object copying in programming?
sobes.tech AI
Answer from AI
In Java, copying an object can be implemented in several ways:
-
Shallow copy — only primitive fields and references to objects are copied, which the original object references. To do this, a class can implement the
Cloneableinterface and override theclone()method. -
Deep copy — new objects are created for all nested objects so that the copy is completely independent.
Example of shallow copying using clone():
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();
}
// getters and setters
}
// Usage:
Person p1 = new Person("Ivan", 30);
Person p2 = (Person) p1.clone();
For deep copying, you can manually create new objects for all nested fields or use serialization.
It is important to remember that the clone() method is not always convenient and safe, so copying constructors or object copying libraries are often used.