Clone Without Super.clone
ID |
java.clone_no_super |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Java |
Tags |
CWE:580, clone, reliability |
Rationale
Object.clone() performs the field-by-field shallow copy that the Cloneable contract documents. Bypassing it (e.g. by new MyClass() and copying fields manually) leaves any inherited state from the superclass in its default-constructed state, which silently corrupts the cloned instance and breaks the contract for subclasses to rely on.
// Bad — bypasses Object.clone, loses superclass state
@Override
public Object clone() {
MyClass copy = new MyClass();
copy.value = this.value;
return copy;
}
// Good — chains through super.clone
@Override
public Object clone() throws CloneNotSupportedException {
MyClass copy = (MyClass) super.clone();
// subsequent deep-copy steps for mutable fields, if needed
return copy;
}