作为我们的作业,我们被要求实现一个带有clone
方法的抽象类。函数的框架如下:
/**
* @effects Creates and returns a copy of this.
*/
public Object clone() {
// TODO: Implement this method
}
< p > Shape
类有两个字段:
private Point location;
private Color color;
在说明中,我们被告知这个方法不会抛出CloneNotSupportedException异常,并且被问及为什么。在互联网上我们看到的所有示例中,克隆方法确实会抛出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;
}
在(Shape)super.clone()
部分会出现错误,显示:
未处理的异常类型 CloneNotSupportedException
,我们应该如何创建克隆方法?