方法 clone() 應調用 super.clone() 獲取新的對象。
在所有實現 clone() 的方法中,應通過調用 super.clone() 來獲取新對象。如果類沒有遵守該約定,那么子類的 clone() 方法將會返回一個錯誤的對象類型。
例 1:以下兩個類顯示了由于沒有調用 super.clone() 而產生的 bug。由于 Kibitzer 實現 clone() 的方法的緣故,FancyKibitzer 的克隆方法將會返回類型為 Kibitzer 而非 FancyKibitzer 的對象。
public class Kibitzer implements Cloneable {
public Object clone() throws CloneNotSupportedException {
Object returnMe = new Kibitzer();
...
}
}
public class FancyKibitzer extends Kibitzer
implements Cloneable {
public Object clone() throws CloneNotSupportedException {
Object returnMe = super.clone();
...
}
}
[1] Standards Mapping - Common Weakness Enumeration - (CWE) CWE ID 580