...
Code Block | ||
---|---|---|
| ||
public final class MutableClass implements Cloneable { private Date date; public MutableClass(Date d) { this.date = new Date(d.getTime()); //copy-in } public Date getDate() { return (Date)date.clone(); //copy and return } public Object clone() throws CloneNotSupportedException { final MutableClass cloned = (MutableClass)super.clone(); cloned.date = (Date)date.clone(); //copy mutable Date object manually return cloned; } } |
Note that the clone()
method must manually clone the Date
object. This step is unnecessary for primitive fields and fields which refer to immutable objects.
A mutable class that defines a clone()
method must be declared final
. This ensures that untrusted code cannot subclass and override the clone()
method to supply a spurious instance. The clone()
method should copy all internal mutable state as necessary. In this compliant solution, the Date
object is copied.
...