对象克隆错误

jan*_*sad 0 java clone

有疑问请澄清我让我解释一下A班和B班2班

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 {

}
Run Code Online (Sandbox Code Playgroud)

当我编译此代码得到以下错误

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

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

小智 5

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

b.clone()为失败,clone是受保护的,因此不是外提供B一流的,除非它会被公开覆盖B.

是关于该clone方法的Javadoc .