Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy constructor v. implementing Cloneable interface

In terms of "best practices", which methodology is preferred for creating a "deep copy" of an object?

like image 624
mre Avatar asked Dec 27 '11 23:12

mre


1 Answers

Use a copy constructor. Cloneable is a straight-up API disaster. See Effective Java Item 10 (Item 11 in the 2nd. ed.).

Item 11: Override clone judiciously

The Cloneable interface was intended as a mixin interface (item 18) for objects to advertise that they permit cloning. Unfortunately, it fails to serve this purpose. Its primary flaw is that it lacks a clone method, and Object's clone method is protected. You cannot, without resorting to reflection (Item 53), invoke the clone method on an object merely because it implements Cloneable. Even a reflective invocation may fail, as there is no guarantee that the object has an accessible clone method.

like image 142
Matt Ball Avatar answered Nov 11 '22 17:11

Matt Ball