Junior — Middle
What methods can be used to create an exact copy of an object in programming?
sobes.tech AI
Answer from AI
In Java, creating an exact copy of an object can be done in several ways:
- Implementing the
Cloneableinterface and overriding theclone()method — creates a shallow copy of the object.
public class Person implements Cloneable {
private String name;
public Person(String name) {
this.name = name;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
- Copy constructor — creating a new object by copying fields from an existing one.
public class Person {
private String name;
public Person(Person other) {
this.name = other.name;
}
}
-
Serialization and deserialization — create a deep copy by writing the object to a stream and reading it back.
-
Using third-party libraries — for example, Apache Commons Lang
SerializationUtils.clone().
It is important to understand the difference between shallow and deep copying, especially if the object contains references to other objects.