Versions Compared

Key

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

Wiki Markup
            Programmers sometimesmay incorrectly believeunderstand that declaring a field or variable {{final}} makes the referenced object immutable. Declaring variables that have a primitive type to be {{final}} does prevent changes to their values after initialization (other than through the use of the unsupported {{sun.misc.Unsafe}} class). However, when the variable has a reference type, the presence of a {{final}} clause in the declaration only makes _the reference itself_ immutable. The {{final}} clause has no effect on the referenced object. Consequently, the fields of the referenced object can be mutable. For example, according to the Java Language Specification \[[JLS 2005|AA. Bibliography#JLS 05]\], [Section 4.12.4|http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#4.12.4], "{{final}} Variables":

...

When an object reference is declared final, it signifies only that the reference cannot be changed; the mutability of the referenced object remains is unaffected.

Compliant Solution (final Fields)

...

The clone() method returns a copy of the original object that reflects the state of the original object at the moment of cloning. This new object can be freely used without exposing the original object; because the caller holds the only reference to the newly cloned instance, the instance fields cannot be changed without the caller's cooperation. This use of the clone() method allows the class to remain securely mutable. (See guideline OBJ10-J. Provide mutable classes with copy functionality to allow passing instances to untrusted code safely.)

The Point class is declared final to prevent subclasses from overriding the clone() method. This enables the class to be suitably used without any inadvertent modifications of the original object. This compliant solution also complies with guideline OBJ10-J. Provide mutable classes with copy functionality to allow passing instances to untrusted code safely.

...

This compliant solution makes the array private, and provides a public methods to get individual items and array size. Providing direct access to the array objects themselves is safe because String is immutable.

...

Neither the original array values nor the public list can be modified by a client. For more details about unmodifiable wrappers, refer to guideline SEC14-J. Provide sensitive mutable classes with unmodifiable wrappers. This solution would still be useful applies if the array contained contains mutable items instead of String.

...