作为我们作业的一部分,我们被要求用clone方法实现一个抽象类.该函数的框架给出:
/**
* @effects Creates and returns a copy of this.
*/
public Object clone() {
// TODO: Implement this method
}
Run Code Online (Sandbox Code Playgroud)
该Shape课程有两个字段:
private Point location;
private Color color;
Run Code Online (Sandbox Code Playgroud)
根据指示,我们被告知该方法不会抛出CloneNotSupportedException异常,并且还会被问到为什么会这样.在我们在互联网上看到的所有示例中,clone方法确实抛出了一个CloneNotSupportedException.
您能否指出我们为什么这个克隆方法不应抛出该异常的原因.
我们编写的方法是:
/**
* @effects Creates and returns a copy of this.
*/
public Object clone() {
Shape new_shape = (Shape)super.clone();
new_shape.setColor(this.getColor());
new_shape.location = (Point)location.clone();
return new_shape;
}
Run Code Online (Sandbox Code Playgroud)
这给了我们一个错误(Shape)super.clone(),说:
Unhandled exception type CloneNotSupportedException,我们应该如何创建克隆方法?
未处理的异常类型CloneNotSupportedException
那是因为定义中的clone()方法Object抛出CloneNotSupportedException:
protected Object clone() throws CloneNotSupportedException
Run Code Online (Sandbox Code Playgroud)
请参阅API文档: Object#clone()
要解决这个问题,您需要使用try/catch块来处理它,或者通过添加throws子句来重新定义它.
更新:
在说明中,我们被告知该方法不会抛出CloneNotSupportedException异常,并且还会询问它为什么会这样.
IMO -
Cloneable接口时,它告诉Object类可以克隆它.在这种情况下,方法的正确实现clone应该调用该super.clone方法.现在,您可以看到它实际上clone是Object类中实际复制的方法.所以,我们应该Object.clone()抛弃它CloneNotSupportedException.如果层次结构中的任何类没有实现Cloneable接口,它将执行此操作.我希望这是有道理的.
即使它有点大,如果你想更多地阅读它.它在Effective Java中进行了解释- 第10项:明智地覆盖克隆.
| 归档时间: |
|
| 查看次数: |
8945 次 |
| 最近记录: |