【问题标题】:Object cloning error对象克隆错误
【发布时间】:2014-12-11 10:28:45
【问题描述】:

有疑问请澄清 让我解释 有 2 类 A 类和 B 类

public class A implements Cloneable{

    public static void main(String[] args) {

        A a1 = new A();
        try {
            A a2 = (A) a1.clone();//works fine
        } catch (CloneNotSupportedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        B b1 = new B();
        B b2 = (B) b1.clone();//cannot get this method

    }

}

class B implements Cloneable {

}

当我编译这段代码时出现以下错误

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
The method clone() from the type Object is not visible

我知道这两个类都扩展了 Java.lang.Object 类 请解释为什么class B不能得到clone()方法

【问题讨论】:

  • IIRC 你必须实现一些特殊的接口来允许克隆。 “可克隆”之类的,不确定
  • 这里没有内部类。

标签: java clone


【解决方案1】:

clone() 方法受到保护。由于您的 main 是 A 类的一部分,因此它允许在 A 类型的对象上调用受保护的方法,因此 a.clone() 可以正常工作。

b.clone() 失败,因为 clone 受到保护,因此在 B 类之外不可用,除非它会被 B 公开覆盖。

Here 是关于 clone 方法的 Javadoc。

【讨论】:

    猜你喜欢
    • 2016-05-29
    • 2016-11-24
    • 2011-11-07
    • 2013-01-03
    • 2017-02-11
    • 2011-07-10
    • 1970-01-01
    • 1970-01-01
    • 2021-02-13
    相关资源
    最近更新 更多