I'm trying to understand what's happening underneath the clone() method in java, I would like to know how is better than doing a new call
public class Person implements Cloneable {
private String firstName;
private int id;
private String lastName;
//constructors, getters and setters
@Override
protected Object clone() throws CloneNotSupportedException {
Person p = (Person) super.clone();
return p;
}
}
this is my clone code i would like to know what's happening underneath and also what's the difference between a new call because.
this is my client code
Person p = new Person("John", 1, "Doe");
Person p2 = null;
try {
p2 = (Person) p.clone();
} catch (CloneNotSupportedException ex) {
Logger.getLogger(clientPrototype.class.getName()).log(Level.SEVERE, null, ex);
}
p2.setFirstName("Jesus");
System.out.println(p);
System.out.println(p2);
clone()
in the first place. – Satyr.clone()
(assuming it usesObject.clone()
underneath) is that it produces an object with the same runtime class as the object it is called on, whereas if you usenew
you would be hard-coding at compile-time the class of object you are creating, which may not be the same as the exact runtime class of the object (the object's class can be a subclass of the compile-time type of a variable that points to it). – Rigamaroleclone
, try to avoid it at all cost. It is a broken feature, super easy to introduce bugs and extremely hard to implement correct. And even harder to maintain a correct implementation with inheritance in place (Effective Java has a nice read on that topic). There are much more safer and better ways for creating copies. For example by introducing a copy constructor to your class. – Underwaist