我正在编写一个类,我必须使用臭名昭着的“super.clone()策略覆盖clone()方法”(这不是我的选择).
我的代码看起来像这样:
@Override
public myInterface clone()
{
myClass x;
try
{
x = (myClass) super.clone();
x.row = this.row;
x.col = this.col;
x.color = this.color;
//color is a final variable, here's the error
}
catch(Exception e)
{
//not doing anything but there has to be the catch block
//because of Cloneable issues
}
return x;
}
一切都会好的,除了我不能在不使用构造函数的情况下初始化颜色,因为它是一个最终的变量……是否有某种方法可以使用super.clone()和复制最终变量?
最佳答案 自调用super.clone();已经创建了所有字段的(浅)副本,最终与否,您的完整方法将变为:
@Override
public MyInterface clone() throws CloneNotSupportedException {
return (MyInterface)super.clone();
}
这要求超类也正确实现clone()(以确保super.clone()最终到达Object类.所有字段都将被正确复制(包括最终字段),如果您不需要深度克隆或任何其他特殊功能,你可以使用它,然后承诺你永远不会尝试再次实现clone()(其中一个原因是正确实现它并不容易,从这个问题可以看出).