Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
bgColor#ccccff
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;
  }
}

Wiki Markup
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
 usually unnecessary when the object contains only primitive fields or fields that refer to immutable objects. When the fields contain data such as unique identifiers or object creation times, the new values of the fields must be calculated and assigned manually in the {{clone()}} method \[[Bloch 08|AA. Java References#Bloch 08]\].

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.

...

Wiki Markup
\[[API 06|AA. Java References#API 06]\] [method clone()|http://java.sun.com/javase/6/docs/api/java/lang/Object.html#clone()]
\[[Security 06|AA. Java References#Security 06]\]
\[[SCG 07|AA. Java References#SCG 07]\] Guideline 2-2 Support copy functionality for a mutable class
\[[SCG 09|AA. Java References#SCG 09]\] Guideline 2-3 Support copy functionality for a mutable class
\[[Bloch 08|AA. Java References#Bloch 08]\] Item 39: Make defensive copies when needed and Item 11: Override clone judiciously
\[[MITRE 09|AA. Java References#MITRE 09]\] [CWE ID 374|http://cwe.mitre.org/data/definitions/374.html] "Mutable Objects Passed by Reference", [CWE ID 375|http://cwe.mitre.org/data/definitions/375.html] "Passing Mutable Objects to an Untrusted Method"

...