为什么我们不能在 class 中使用克隆方法而不实现可克隆,即使基础 class 对象具有 "clone()" 方法?

Why cant we use clone method in class without implementing clonable as even though base class object has "clone()" method?

我试图在我的 class "Employee" 中重写克隆方法,当 super.clone() 被调用时,它给出了异常,但是当我实现 [=19= 时相同的代码有效].我的问题是,每个 class 都有基数 class "Object"。但是当我们调用 super.clone() 时它失败了并且在实现可克隆时它起作用了。为什么会这样?

好像不应该可以使用 subclass 中的 "super" 访问 base class 方法?为什么会抛出运行时异常?

public class Employee {
    //explicit Employee extends Object didn't worked. 
    String name;
    Integer id;
    public Employee(String name, Integer id) {
       this.name = name;
       this.id = id;
     }
    @Override
    protected Object clone() throws CloneNotSupportedException {
      return super.clone();
    }
  }

要回答您的问题,请查看 Object class reference page,您会看到:

The class Object does not itself implement the interface Cloneable, so calling the clone method on an object whose class is Object will result in throwing an exception at run time.

所以您描述的行为正是 Java 所定义的。不确定这里还有什么令人困惑的地方。

查看 Whosebug answer:

The implementation of clone() in Object checks if the actual class implements Cloneable, and creates an instance of that actual class.

So if you want to make your class cloneable, you have to implement Cloneable and downcast the result of super.clone() to your class. Another burden is that the call to super.clone() can throw a CloneNotSupportedException that you have to catch, even though you know it won't happen (since your class implements Cloneable).

The Cloneable interface and the clone method on the Object class are an obvious case of object-oriented design gone wrong.