Clone Must Be Public

ID

java.clone_must_be_public

Severity

info

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Java

Tags

clone, reliability

Description

Reports clone() methods that are not declared public. The clone() method should always be accessible to callers.

Rationale

Restricting the visibility of clone() (to protected or private) prevents callers from creating copies through the standard Cloneable mechanism. Since Object.clone() is protected, subclasses that override it should widen access to public.

// Bad — restricted visibility
protected Object clone() throws CloneNotSupportedException {
    return super.clone();
}

Remediation

Declare the clone() method as public:

// Good
public Object clone() throws CloneNotSupportedException {
    return super.clone();
}