Java Reference
In-Depth Information
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 used without expos-
ing the original object. Because the caller holds the only reference to the newly cloned
instance, the instance variables cannot be changed without the caller's cooperation. This
use of the
clone()
method allows the class to remain securely mutable. (See
The CERT
®
Oracle
®
Secure Coding Standard for Java
™
[Long 2012], “OBJ04-J. Provide mutable
classes with copy functionality to safely allow passing instances to untrusted code.”)
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.
Noncompliant Code Example (Arrays)
This noncompliant code example uses a
public static final
array,
items
:
public static final String[] items = {/* . . . */};
Clients can trivially modify the contents of the array, even though declaring the array
reference to be
final
prevents modification of the reference itself.
Compliant Solution (Index Getter)
This compliant solution makes the array
private
and provides public methods to get in-
dividual items and array size:
private static final String[] items = {/* . . . */};
public static final String getItem(int index) {
return items[index];
}
public static final int getItemCount() {
return items.length;
}
Providing direct access to the array objects themselves is safe because
String
is im-
mutable.