Subclass error: CloneNotSupportedException never being thrown in the try body

Subclass error: CloneNotSupportedException never being thrown in the try body

我现在正在上交关于继承和深度克隆的内容。

上交是关于使用继承和深度克隆的思想重写提供给我们的代码,使用将形状绘制为 canvas.

的程序

现在我已经为超类 point 和我的子类 group 实现了 clone() 方法,但我总是得到 CloneNotSupportedExceptionclone() 在我的子类中编译时,我真的不明白为什么。

这是我的超类的代码:

public abstract class Point implements Cloneable
{
public Point clone() 
    {
        try {
             Point copy = (Point)super.clone();
             copy.imgGroup = (ArrayList<Point>)imgGroup.clone();
             return copy;
        }
        catch (CloneNotSupportedException e) {
            throw new InternalError();
        }
     }
}

这是我的子类的代码:

public class Group extends Point implements Cloneable
{
public Group clone() 
    {
        try {
            Group copy = (Group)super.clone();
            copy.group = (ArrayList<Point>)group.clone();
            for (int i = 0; i < group.size(); i++) {
                copy.group.set(i,group.get(i).clone());
            }
            return copy;
        }
        catch (CloneNotSupportedException e) {
            throw new InternalError();
        }
    }
}

任务:

构造ClassGroup。可以将某个 Figure 对象添加到多个不同的组中。您必须确定同一个 Figure 对象是否可以同时属于多个组。在本练习中,不应发生这种情况。所有 Group 对象必须独占其项目对象。不得在多个组之间共享对象。

因此,我们开始添加方法:

public Figure class clone ();
// (define it in the same style as on page 4 in the document below)
// this was what point clone() was in the class Point.

之后是一些方法的实施说明和 Group 克隆。

所以在这个任务中,我应该用各种方法实现 Group 以及一个新的 clone(),这就是我现在遇到的问题。

我希望你能帮我指明正确的方向,只是想知道为什么会这样。谢谢!

I always get a CloneNotSupportedException with the clone() in my subclass

我想你得到的是; Unreachable catch block for CloneNotSupportedException.

那是因为你在超级 class 签名中省略了 throws CloneNotSupportedException。但是,在子 class 中,您希望 super.clone() 抛出选中的 CloneNotSupportedException。将您的超级 class 实现更改为;

public abstract class Point implements Cloneable {
    public Point clone() throws CloneNotSupportedException { 
        Point copy = (Point) super.clone(); 
        return copy;
    }
}

这样子 class.class.

可以看到超级 class 签名中抛出的异常

更新

为了更加清楚,请遵循下面的

更新 2

添加更多详细信息,因为其他答案已被用户删除(我上面的评论指的是)。

您不能实例化一个抽象 class - 但您仍然可以在其中包含一个 clone() 方法。但是抽象 class 在其克隆方法中应该 return 的具体克隆实例是什么?当你在摘要 class 中说 thissuper.clone() 时,这两个都指的是 运行 时的同一个子 class 实例。这意味着浅拷贝 (Point copy = (Point) super.clone();) 在您的例子中是 Group 的一个实例。您可以在抽象超级 class' clone 方法中添加 System.out.println(super.clone().getClass()) 来证明这一点。

因此您可以在超级抽象 class 中深度克隆可继承的属性 - 并且 - 在 subclass' clone() 方法中仅深度克隆 subclass' 属性。这样,如果您定义了多个子class,就可以避免在所有子class中深度克隆超级class属性。