The Java documentation says:
A class implements the Cloneable interface to indicate to the Object.clone() method that it is legal for that method to make a field-for-field copy of instances of that class.
Invoking Object's clone method on an instance that does not implement the Cloneable interface results in the exception CloneNotSupportedException being thrown.
By convention, classes that implement this interface should override Object.clone (which is protected) with a public method. See Object.clone() for details on overriding this method.
Note that this interface does not contain the clone method. Therefore, it is not possible to clone an object merely by virtue of the fact that it implements this interface. Even if the clone method is invoked reflectively, there is no guarantee that it will succeed.
And I have this UserProfile
class:
public class UserProfile implements Cloneable {
private String name;
private int ssn;
private String address;
public UserProfile(String name, int ssn, String address) {
this.name = name;
this.ssn = ssn;
this.address = address;
}
public UserProfile(UserProfile user) {
this.name = user.getName();
this.ssn = user.getSSN();
this.address = user.getAddress();
}
// get methods here...
@Override
public UserProfile clone() {
return new UserProfile(this);
}
}
And for testing porpuses, I do this in main()
:
UserProfile up1 = new UserProfile("User", 123, "Street");
UserProfile up2 = up1.clone();
So far, no problems compiling/running. Now, per my understanding of the documentation, removing implements Cloneable
from the UserProfile
class should throw an exception in up1.clone()
call, but it doesn't.
I've read around here that the Cloneable interface is broken but I don't really know what that means. Am I missing something?