The software contains a clone() method that fails to call
super.clone() to obtain the new object.
Extended Description
All implementations of clone() should obtain the new object by calling
super.clone(). If a class fails to follow this convention, a subclass's
clone() method will return an object of the wrong type.
Time of Introduction
Implementation
Applicable Platforms
Languages
Java
Demonstrative Examples
Example 1
The following two classes demonstrate a bug introduced by failing to
call super.clone(). Because of the way Kibitzer implements clone(),
FancyKibitzer's clone method will return an object of type Kibitzer instead
of FancyKibitzer.
(Bad Code)
Java
public class Kibitzer {
public Object clone() throws CloneNotSupportedException
{
Object returnMe = new Kibitzer();
...
}
}
public class FancyKibitzer extends Kibitzer{
public Object clone() throws CloneNotSupportedException
{
Object returnMe = super.clone();
...
}
}
Potential Mitigations
Phase
Description
Implementation
Call super.clone() within your clone() method, when obtaining a new
object.
Implementation
In some cases, you can eliminate the clone method altogether and use
copy constructors.