Copy Constructor vs Cloneable. Why shouldn't I consider Cloneable?

Rav*_*avi 3 java object copy-constructor cloneable

I was reading this answer and he mentioned a link, where author explains why shouldn't we use Cloneable. But, still have doubt what was stated there

如果我有一个 Cloneable 数组,您会认为我可以运行该数组并克隆每个元素以制作该数组的深层副本,但我不能。您不能将某些内容强制转换为 Cloneable 并调用克隆方法,因为 Cloneable 没有公共克隆方法,而 Object 也没有。如果您尝试转换为 Cloneable 并调用克隆方法,编译器会说您正在尝试调用对象上受保护的克隆方法。

但是,我在这里做到了

        Init s = Init.getInstance(); // getting instance
        int count=0;
        Cloneable[] v = new Cloneable[5]; // creating array
        Init x = s;
        Init y = new Init(s);
        try {
            while (count < 5) {
                v[count++] =  (Cloneable) s.clone(); // casting it.
            }

            s.setClassName("Example");
            System.out.println(((Init) v[2]).getClassName()); // Displaying.
        } catch (CloneNotSupportedException ex) {
            ex.printStackTrace();
        }
Run Code Online (Sandbox Code Playgroud)

我能够创建 Cloneable 数组,并且我做了作者所说的会导致错误的操作,或者我是否误解了作者的声明?任何人,请帮助我理解选择复制构造函数而不是可克隆的原因。

Cod*_*der 5

您不是s先投射Cloneable然后调用clone()它。

相反,您正在调用s.clone(),然后将结果转换为Clonable. 你能够做到这一点是因为s它有类型Init并且Initpublic clone()方法。

相反,这样做你会发现编译器大喊:

 v[count++] =  ((Cloneable) s).clone();
Run Code Online (Sandbox Code Playgroud)

现在假设您要克隆一个数组(您显然只知道它是一个Cloneable数组。这意味着您不知道它的实际类型。

Cloneable[] cloneArray = new Cloneable[5];
cloneArray[i] = new Init(); // Let's say it's initialized with different type objects but all `Cloneable`.

for (Cloneable object : cloneArray) {
      object.clone(); // Compiler wont allow it. And you don't know what type it is.
}
Run Code Online (Sandbox Code Playgroud)

因此,您基本上无法深度克隆 Cloneable 数组。