Implement Cloneable When Overriding Clone

ID

java.clone_must_implement_cloneable

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Java

Tags

clone, reliability

Description

Reports classes that override clone() without implementing java.lang.Cloneable. Calling clone() on a non-Cloneable class throws CloneNotSupportedException.

Rationale

Object.clone() checks whether the class implements Cloneable. If it does not, the method throws CloneNotSupportedException at runtime. Overriding clone() without the marker interface is confusing and likely a bug.

// Bad — no Cloneable interface
public class MyClass {
    public Object clone() throws CloneNotSupportedException {
        return super.clone(); // throws at runtime
    }
}

Remediation

Add implements Cloneable to the class declaration:

// Good
public class MyClass implements Cloneable {
    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}